SSC - Communication and Networking
SSC - Concurrency and Multi-threading Concurrency in Swing
Shan He
School for Computational Science University of Birmingham
Module 06-19321: SSC SSC - Communication and Networking Outline
Outline of Topics
Concurrency in Swing SSC - Communication and Networking Concurrency in Swing
Responsive or Unresponsive UI?
I Screen liveliness: users expect a program is always responsive, no matter what it’s doing
I But let’s take a look at a BAD example
I Swing is a single-threaded programming model
I Event-dispatch thread: handles all interaction events. I How the Swing works:
I Step 1: Swing generates event objects that contain relevant event information, e.g. event source and event ID. I Step 2: placed event objects to a single event queue ordered by their entry time. I Step 3: event-dispatch thread, regularly checks and takes event objects from the queue one by one and sends them to the interested parties I Step 4: the interested parties react to the event notification SSC - Communication and Networking Concurrency in Swing
How the Swing works:
Event queue Event n Queue up events Event n-1 Event n-2 …
Update UI Event 2 Event 1 Event listener
List Selection Listener Event dispatch thread
Paint Others Notifies interested parties SSC - Communication and Networking Concurrency in Swing
Let’s trace the threads
I We can tracing the threads executed in a Swing application I Five thread involved:
I Main thread by the main() method I “AWT-Windows” (daemon thread): listen to UI events from AWT windows I “AWT-Shutdown”: Handling the exit of AWT windows, e.g., terminates the event dispatch thread and exits I “AWT-EventQueue-0”: Event-Dispatching Thread, which is the one and only thread responsible for handling all the events I “DestroyJavaVM”: Handling the exit of the main thread after the main() method completes
I NOTE: AWT (Abstract Window Toolkit) is the original Java platform-independent windowing, graphics, and user-interface widget toolkit SSC - Communication and Networking Concurrency in Swing
What threads you can create/control in Swing?
I Two threads created automatically by Java:
I Main thread by the main() method I “AWT-EventQueue-0”: Event-Dispatching Thread, which is the one and only thread responsible for handling all the events
I Plus other threads you created in Swing: called worker thread SSC - Communication and Networking Concurrency in Swing
How to write an unresponsive Swing?
I Do everything, esp. time consuming tasks in the Event-Dispatching Thread
I Essentially add time consuming tasks in the actionPerformed method of the Swing component SSC - Communication and Networking Concurrency in Swing
Bad Swing programme:
Small tasks
Time
Click button Time-consuming tasks
One single event dispatch thread SSC - Communication and Networking Concurrency in Swing
How to make Swing responsive?
I Responsive principle: Use threads other than event dispatch thread to execute time-consuming background tasks
I Such thread are called Worker threads, also known as background threads However SSC - Communication and Networking Concurrency in Swing
Swing is not thread safe!
I Why Swing is not thread safe?: invoking some Swing components from multiple threads will cause thread interference or memory consistency errors.
I Note: “It may seem strange that such an important part of the Java platform is not thread safe. It turns out that any attempt to create a thread-safe GUI library faces some fundamental problems”; also MultiThreaded toolkits: A failed dream? I Safe principle: ONLY create and update Swing components from the Event Dispatch thread
I The same principle applies to those models used by Swing components e.g. ListModel (JList), TableModel (JTable) I The code ignore the above safe principle might work, but might produce unpredictable errors that are difficult to reproduce. I Two ways to implement the safe principle:
I SwingUtilities.invokeLater()
I SwingWorker SSC - Communication and Networking Concurrency in Swing
SwingUtilities.invokeLater()
I From the Safe principle, user interface updates must ONLY happen in the event dispatch thread.
I Jobs carried out in other threads cannot update Swing components
I Problem: in a time-consuming task, we need to update Swing components to give user some feedback, e.g., a progress bar
I Solution: To use SwingUtilities.invokeLater in your worker thread to post a ”job” to Swing, which it will then run on the event dispatch thread at its next convenience. SSC - Communication and Networking Concurrency in Swing
How SwingUtilities.invokeLater() works
Event Dispatch Thread SwingUtilities.invokeLater(new Runnable() { public void run() { InvokeLaterSwingExample.this.tfCount. setText("Count is " + count); } }); Worker Thread SSC - Communication and Networking Concurrency in Swing
SwingUtilities.invokeLater()
I From Oracle:“Causes runnable to have its run method called in the dispatch thread of the system EventQueue. This will happen after all pending events are processed. ”
I After calling invokeLater() in the worker thread, the code hands over its run method to even dispatch thread and continues to run
I Java example: Update JTextField in a worker thread SSC - Communication and Networking Concurrency in Swing
SwingWorker class
I javax.swing.SwingWorker : An abstract class to perform lengthy GUI-interaction tasks in a background thread. I Simplifies complicated thread communications by a number features:
I SwingWorkerdone() method: automatically invoked on the event dispatch thread when the background task is finished. I implements java.util.concurrent.Future to:
I allow the background task to provide a return value to other threads, I cancel the background task I discover whether the background task has finished or been cancelled.
I SwingWorker.publish() : provides intermediate results
I Defines bound properties by background task: changes to these properties trigger events, causing event-handling methods to be invoked on the event dispatch thread. SSC - Communication and Networking Concurrency in Swing
Good Swing programme:
Small tasks (Swing objects related)
Time
Event dispatch thread Click button
Time
Time-consuming tasks SwingWorker thread SSC - Communication and Networking Concurrency in Swing
How to use SwingWorker
I Class SwingWorker
I V - the type used for carrying out intermediate results by this SwingWorker’s publish and process methods I doInBackground() method: this method is essentially executed in a worker thread, where all background activities should happen I process() method: used to process intermediate results generated in doInBackground
I done() method: used to process the final results returned by doInBackground when it finishes I Question: where can I update Swing components? SSC - Communication and Networking Concurrency in Swing
How to use addPropertyChangeListener
I A bound property notifies listeners when its value changes
I Used for thread communication I Two predefined bound properties in the SwingWorker class: progress and state .
I progress : int value ∈ [0, 100]
I state : A constant indicates where the SwingWorker object is in its lifecycle, can be DONE , PENDING and STARTED
I Use setProgress() to change progress
I Java example: to update progress bar SSC - Communication and Networking Concurrency in Swing
With SwingWorker