ssc - concurrency and multi-threading concurrency in swingszh/teaching/ssc/lecturenotes/... ·...
Post on 21-Jun-2020
1 Views
Preview:
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
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 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 NOTE: AWT (Abstract Window Toolkit) is 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 threads created automatically by Java: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
How to write an unresponsive Swing?
I Do everything, esp. time consuming tasks in theEvent-Dispatching Thread
I Essentially add time consuming tasks in theactionPerformed method of the Swing component
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?
I Responsive principle: Use threads other than event dispatchthread to execute time-consuming background tasks
I Such thread are called Worker threads, also known asbackground 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 threadinterference or memory consistency errors.
I Note: “It may seem strange that such an important part of theJava platform is not thread safe. It turns out that any attemptto create a thread-safe GUI library faces some fundamentalproblems”; also MultiThreaded toolkits: A failed dream?
I Safe principle: ONLY create and update Swing componentsfrom the Event Dispatch thread
I The same principle applies to those models used by Swingcomponents e.g. ListModel (JList), TableModel (JTable)
I The code ignore the above safe principle might work, but mightproduce 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 ONLYhappen in the event dispatch thread.
I Jobs carried out in other threads cannot update Swingcomponents
I Problem: in a time-consuming task, we need to update Swingcomponents to give user some feedback, e.g., a progress bar
I Solution: To use SwingUtilities.invokeLater in yourworker thread to post a ”job” to Swing, which it will then runon the event dispatch thread 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
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
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: this method is essentiallyexecuted in a worker thread, where all background activitiesshould 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 finishesI 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 communicationI 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
top related