ssc - concurrency and multi-threading concurrency in swing · ssc - communication and networking...
TRANSCRIPT
SSC - Communication and Networking
SSC - Concurrency and Multi-threadingConcurrency in Swing
Shan He
School for Computational ScienceUniversity of Birmingham
Module 06-19321: SSC
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 Let’s take a look at an 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 relevantevent information, e.g. event source and event ID.
I Step 2: placed event objects to a single event queue orderedby their entry time.
I Step 3: event-dispatch thread, regularly checks and takesevent objects from the queue one by one and sends them tothe 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 nEvent n-1Event n-2
…
Event 2Event 1
Event queue
Paint
List Selection Listener
Event listener
Event dispatch thread
Others Notifies interested parties
Update UI
Queue up events
SSC - Communication and Networking
Concurrency in Swing
Let’s trace the threads
I We can tracing the threads executed in a Swing applicationI Five thread involved:
I Main thread by the main() methodI “AWT-Windows” (daemon thread): listen to UI events from
AWT windowsI “AWT-Shutdown”: Handling the exit of AWT windows, e.g.,
terminates the event dispatch thread and exitsI “AWT-EventQueue-0”: Event-Dispatching Thread, which is
the one and only thread responsible for handling all the eventsI “DestroyJavaVM”: Handling the exit of the main thread after
the main() method completes
I AWT: Abstract Window Toolkit the original Javaplatform-independent windowing, graphics, and user-interfacewidget toolkit
SSC - Communication and Networking
Concurrency in Swing
What threads you can create/control in Swing?
I Two thread:I Main thread by the main() methodI “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
Bad Swing programme:
Time-consuming tasks
Small tasks
Click button
Time
One single event dispatch thread
SSC - Communication and Networking
Concurrency in Swing
How to make Swing responsive and safe?I Responsive principle: Use threads other than event dispatch
thread to execute time-consuming background tasksI Such thread are called Worker threads, also known as
background threads
I Safe principle: To update user interface, invoke all Swingcomponent methods from the event dispatch thread
I The code ignore the above safe principle might work, but mightproduce unpredictable errors that are difficult to reproduce.
I Most Swing object methods are not “thread safe”: threadinterference or memory consistency errors.
I Never call methods such as Thread.sleep(), Object.wait(),Condition.await() inside an event handler.
I Two ways of doing this:I SwingUtilities.invokeLater()
I SwingWorker
SSC - Communication and Networking
Concurrency in Swing
Good Swing programme:
Time-consuming tasks
Click button
Time
SwingWorker thread
Small tasks (Swing objects related)
Time
Event dispatch thread
SSC - Communication and Networking
Concurrency in Swing
SwingUtilities.invokeLater()
I User interface updates must ONLY happen on the eventdispatch thread.
I Jobs carried out in other threads cannot update Swingcomponents
I Problem: in a time-consuming task, we need to update Swingcomponents
I Solution: To use SwingUtilities.invokeLater to posta ”job” to Swing, which it will then run on the event dispatchthread at its next convenience.
SSC - Communication and Networking
Concurrency in Swing
How SwingUtilities.invokeLater() works
EventDispatchThread
WorkerThread
SwingUtilities.invokeLater(new Runnable() {public void run() {InvokeLaterSwingExample.this.tfCount.setText("Count is " + count);}
});
SSC - Communication and Networking
Concurrency in Swing
SwingUtilities.invokeLater()
I From Oracle:“Causes runnable to have its run method calledin the dispatch thread of the system EventQueue. This willhappen after all pending events are processed. ”
I After calling invokeLater() in the worker thread, thecode hands over its run method to even dispatch thread andcontinues 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 performlengthy GUI-interaction tasks in a background thread.
I Simplifies complicated thread communications by a numberfeatures:
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 otherthreads,
I cancel the background taskI discover whether the background task has finished or been
cancelled.
I SwingWorker.publish() : provides intermediate resultsI Defines bound properties by background task: changes to
these properties trigger events, causing event-handlingmethods to be invoked on the event dispatch thread.
SSC - Communication and Networking
Concurrency in Swing
How to use SwingWorkerI Class SwingWorker<T,V>
I Type Parameters:I T - the result type returned by this SwingWorker’s
doInBackground and get methods
I V - the type used for carrying out intermediate results by thisSwingWorker’s publish and process methods
I doInBackground() method: where all backgroundactivities should happen
I process() method: used to process intermediate results in
doInBackground
I done() method: used to process the final results returned
by doInBackground when it finishesI Question: Can you update Swing components in the above
three methods?
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 communicationI Two predefined bound properties: 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