Alexander Mills
Alexander Mills

Reputation: 99960

Is SwingWorker the only way?

I have found that in order to keep Java GUIs (using Swing) responsive the only way is to use the SwingWorker class, as opposed to java.lang.Thread. Is SwingWorker truly the only way when it comes multithreaded GUI based desktop apps? Are there any good alternatives? Rarely can I configure the Thread class to do what I want to do, but SwingWorker usually works, if sometimes in a cumbersome way.

Upvotes: 1

Views: 347

Answers (4)

Kojotak
Kojotak

Reputation: 2070

Another option, most suitable for repetitive tasks, is javax.swing.Timer (it can be used for one-shot tasks as well).

Upvotes: 2

trashgod
trashgod

Reputation: 205775

The alternative is a continuation using EventQueue.invokeLater(), but SwingWorker has important advantages:

  • It synchronizes granular access to data shared between itself and the EDT.

  • It provides property change support for progress indication.

  • It implements the Future interface.

See also Worker Threads and SwingWorker for details.

Upvotes: 7

Marko Topolnik
Marko Topolnik

Reputation: 200138

SwingWorker is nothing but a thin convenience API around Thread. Therefore it is definitely possible to use Thread without SwingWorker. The main point is that Swing is not thread-safe and any actions you perform on Swing objects must happen on the Event Dispatch Thread. This is the fundamental obstacle, and SwingWorker tries to help you overcome it a bit more conveniently.

Upvotes: 9

Slimu
Slimu

Reputation: 2371

Multithreading in GUI application is difficult to implement since there can be so many actions that trigger actions. A good explanation of why is this a "failed dream" can be found here Multithreaded toolkits: A failed dream.. For solutions to your problem, read this article on concurrency in swing: Concurrency in Swing

Depending on your duration of the action you can go with SwingUtilities.invokeLater() or make a SwingWorker for tasks that take a long time to complete and run in background. You must use this classes or else you may be in situations where a thread will block your entire application and may seem unresponsive to the user.

Upvotes: 3

Related Questions