Results 1 to 3 of 3
  1. #1
    Heatryn is offline Member
    Join Date
    Jun 2012
    Rep Power

    Default Doing background task in Swing application

    Hi everyone.

    I have a client/server application in Swing. The clients sends a request via RMI to send an email to the server on another computer. However I want the server method to redirect directly to the client. Otherwise my Swing application will hang for some time.

    I have done this with a SwingWorker thread and the doInBackground method.

    Java Code:
    	    emailThread = new SwingWorker<Boolean, Boolean>() {
    		protected Boolean doInBackground() throws Exception {
    		    while (!this.isCancelled()) {
    			if (emailQueue.size() > 0) {
    			  //  log("Email versturen...");
    			    log("Email verstuurd naar " + emailQueue.get(0).getToAddresses().get(0) + " met als onderwerp " + emailQueue.get(0).getSubject());
    		    return true;
    I have a class variable with a queue of email messages. Everytime I call the method sendEmail, I just add another email to this queue variable. In the doInBackground method I check continuously if there are some emails in the queue and I send them and remove them afterwards from the queueu. You can see that in the above code.

    This works fine. However there is the problem of performance. When I start the server my CPU usage at the server computer goes to 100% and slows everything down.

    When I put however a Thread.sleep method in the while lus, I have the problem when I want to send 100 emails, that there is a time between every email. So that is not what I want.

    How can I fix this?

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Rep Power

    Default Re: Doing background task in Swing application

    Look into how to use wait/notify. For instance, your worker can wait on the queue, which you can notify when an item is added to the queue. Alternatively, look into the BlockingQueue implementations.

  3. #3
    Heatryn is offline Member
    Join Date
    Jun 2012
    Rep Power

    Default Re: Doing background task in Swing application

    Thank you!

    Works like a charm.

Similar Threads

  1. SwingWorker background task pause
    By madroadbiker in forum Advanced Java
    Replies: 5
    Last Post: 05-07-2011, 07:00 PM
  2. Swing : Background image
    By Java Unknown in forum New To Java
    Replies: 1
    Last Post: 02-24-2011, 10:52 AM
  3. getting running application from task manager
    By gayathri_g in forum Threads and Synchronization
    Replies: 3
    Last Post: 09-26-2009, 06:43 PM
  4. Replies: 0
    Last Post: 04-12-2009, 04:16 PM
  5. java : how to hide application icon from a task bar
    By yogeshagashe in forum Advanced Java
    Replies: 0
    Last Post: 03-12-2008, 02:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts