Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between Java's SwingWorker and Android AsyncTask

I was comparing the differences between Swing's SwingWorker and Android's AsyncTask classes. While Android has a Main Thread/UI Thread and then spawns a background thread (using AsyncTask), SwingWorker has three threads that are involved -

  • Current thread
  • Worker thread
  • Event Dispatch Thread.

And then I also came across the statement (in docs) -

Often, the Current thread is the Event Dispatch Thread.

Now, what does this mean?

Does it mean that Swing also has only 1 thread - the Main Thread and even the events are received on the same thread OR Is it different for different JVM implementations?

like image 516
yadav_vi Avatar asked Dec 15 '14 10:12

yadav_vi


1 Answers

This is only valid for Swing, which shares some similarities with Android UI programming but is indeed not the same.

A little bit of context

The EDT (Event Dispatch Thread) is Swing's thread dedicated to handling UI events (mouse and keyboard input, events on controls, rendering of the UI, etc...). This is an Event Loop model, similar to what is done in Android.

The fact that event listeners in Swing are executed on the EDT is the root cause for freezing UIs in Swing applications: developers misunderstanding the threading model often put long-running code in the listeners, which blocks the EDT and thus the GUI.

SwingWorker was introduced to better guide developers in separating UI updates from long-running background code. It spawns a dedicated background thread for the I/O processing (or long-running task) in doInBackground and executes UI updates in done and process methods. While these 3 methods guarantee in which thread they'll be executed, all other methods are executed in the current thread.

What is meant by the sentence you quoted

The whole reason for SwingWorker to exist is to properly initiate a long-running process from the GUI, without blocking the GUI.

Often, it will be in reaction to a user's input (e.g. clicking a Button). Since reactions to the user's input (implemented as Listeners) are always executed in the EDT by the Swing framework, unless you happen to call execute or get from another thread explicitly, it will get executed on the EDT.

By the way, execute is "fire-and-forget" and is the typical use-case (call it from a listener). get on the other hand blocks, and is not suited to be called from a listener (it would defeat SwingWorker's purpose, call it on your own threads if needed)!

like image 103
Simon Baslé Avatar answered Oct 18 '22 07:10

Simon Baslé