Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the rationale of SwingWorker?

For what I can read, it is used to dispatch a new thread in a swing app to perform some "background" work, but what's the benefit from using this rather than a "normal" thread?

Is not the same using a new Thread and when it finish invoke some GUI method using SwingUtilities.invokeLater?...

What am I missing here?

http://en.wikipedia.org/wiki/SwingWorker

http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html

like image 506
OscarRyz Avatar asked Nov 11 '08 19:11

OscarRyz


2 Answers

Yes, you can accomplish what a SwingWorker does with vanilla threads + invokeLater. SwingWorker provides a predictable, integrated way to accomplish tasks on a background thread and report result on the EDT. SwingWorker additionally adds support for intermediate results. Again, you can do all of this yourself but sometimes it's easy to use the integrated and predictable solution especially when it comes to concurrency.

like image 178
basszero Avatar answered Sep 28 '22 03:09

basszero


A code example:

import org.jdesktop.swingx.util.SwingWorker; // This one is from swingx
                                             // another one is built in 
                                             // since JDK 1.6 AFAIK?

public class SwingWorkerTest {

  public static void main( String[] args ) {

    /**
      * First method
      */
    new Thread() {

      public void run() {

        /** Do work that would freeze GUI here */

        final Object result = new Object();
        java.awt.EventQueue.invokeLater( new Runnable() {

          public void run() {
          /** Update GUI here */
          }
        } );

      }
    }.start();

    /**
      * Second method
      */
    new SwingWorker< Object , Object >() {

      protected Object doInBackground() throws Exception {
        /** Do work that would freeze GUI here */

        return null;
      }

      protected void done() {
        try {
          Object result = get();
          /** Update GUI here */
        }
        catch ( Exception ex ) {
          ex.printStackTrace();
          if ( ex instanceof java.lang.InterruptedException )
            return;
        }
      }
    }.execute();
  }

}

The choice always depends on personal preference and use case.

The second method has an advantage when refactoring. You can more easily convert the anonymous class to an inner class when the method it's used in is too large.

My personal preference goes to the second, for we have built a framework where SwingWorkers can be added and are executed one after the other...

like image 38
Daniel Hiller Avatar answered Sep 28 '22 02:09

Daniel Hiller