What are the advantages of using SwingWorker
instead of Thread
or Runnable
?

- 4,205
- 7
- 36
- 56
4 Answers
I think the documentation of the SwingWorker is pretty good:
An abstract class to perform lengthy GUI-interacting tasks in a dedicated thread.
When writing a multi-threaded application using Swing, there are two constraints to keep in mind: (refer to How to Use Threads for more details):
- Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive.
- Swing components should be accessed on the Event Dispatch Thread only.
These constraints mean that a GUI application with time intensive computing needs at least two threads: 1) a thread to perform the lengthy task and 2) the Event Dispatch Thread (EDT) for all GUI-related activities. This involves inter-thread communication which can be tricky to implement.
SwingWorker is designed for situations where you need to have a long running task run in a background thread and provide updates to the UI either when done, or while processing. Subclasses of SwingWorker must implement the doInBackground() method to perform the background computation.
surely you can do this using Thread, Runtime and SwingUtilities (invokeLater
) but it's easier and probably less error prone using the SwingWorker class.

- 28,957
- 10
- 64
- 87
SwingWorker takes care of some details, like UI updates while running the task, or after task finishes. These must be executed on Swing EDT thread. You can do it yourself, but it's too easy to do it wrong.

- 32,463
- 16
- 90
- 116
Thread and Runnable were part of Java 1.0; they're as good as they were back then.
The new concurrency classes distill all that's been learned about multi-threading since then (thank you, Doug Lea and others). Writing multi-threaded code is terribly difficult. The new concurrency classes, including SwingWorker, try to make that easier.
Start by noting the generics for strong typing. There's a mechanism built in to publish and process both final and intermediate results.
It'd be possible to mimic these with Thread and Runnable, but SwingWorker has done it for you.

- 305,152
- 44
- 369
- 561
-
1is SwingWorker really part of the new concurrency classes? I think it's part of the Swing API and the main reason for using it is because of the constraints regarding the Event Dispatch Thread (EDT). – user85421 Dec 23 '10 at 12:44
-
1Not part of the concurrency package, but I'd consider it in the same spirit. Could be wrong. – duffymo Dec 23 '10 at 12:49
SwingWorker
encapsulates correct interaction with the event dispatching thread. Runnable
doesn't.

- 305,947
- 44
- 307
- 483