7

May be this is trivial, I am struggling to understand a simple documentation on SwingWorker.

Here is the copy pasted content

Workflow

There are three threads involved in the life cycle of a SwingWorker :

Current thread: The execute() method is called on this thread. It schedules SwingWorker for the execution on a worker thread and returns immediately. One can wait for the SwingWorker to complete using the get methods.

Worker thread: The doInBackground() method is called on this thread. This is where all background activities should happen. To notify PropertyChangeListeners about bound properties changes use the firePropertyChange and getPropertyChangeSupport() methods. By default there are two bound properties available: state and progress.

Event Dispatch Thread: All Swing related activities occur on this thread. SwingWorker invokes the process and done() methods and notifies any PropertyChangeListeners on this thread.

Often, the Current thread is the Event Dispatch Thread.

--

The worker thread is not the EDT, hence the code in doInBackground() must not access GUI elements. Is my understanding correct?

Background: We have small code that uses SwingWorker but has doInBackground() createing FileChooser and calling setCurrentDirectory(). I suspect that is leading me exception almost same as http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6637181 ( 11-Closed, Not a Defect)

Jayan
  • 18,003
  • 15
  • 89
  • 143

1 Answers1

13

Yes. From a background thread - both regular threads and SwingWorker.doInBackground you must not modify the UI to avoid various trouble.

Instead, wrap the changes in a Runnable and have them executed in the EDT via SwingUtilities.invokeAndWait, SwingUtilities.invokeLater or - when using SwingWorker - via publish (from doInBackground). Within the process method of SwingWorker, which is executed by the EDT, you may access the GUI.

http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html

Personally, I find invokeLater and invokeAndWait easier to use for many situations. SwingWorker is okay for e.g. progress bars.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
  • Thanks- we do what you wrote in answer almost all places. There some some areas where the code uses swingworker. Even in those case, the processing could be split into GUI accessing and non-gui part. – Jayan Jan 24 '12 at 08:22
  • Doing the split right will usually increase performance and avoid problems, so it is strongly recommended. – Has QUIT--Anony-Mousse Jan 24 '12 at 08:25
  • @Jayan tutorial talking about output from publish / process / done, you can test that if(isEventDispatchThread) please read http://stackoverflow.com/questions/7053865/cant-get-arrayindexoutofboundsexception-from-future-and-swingworker-if-threa . +1 – mKorbel Jan 24 '12 at 08:30