120 likes | 329 Views
Keeping your Swing Applications Responsive using FoxTrot and Friends. Rob Ratcliff. Swing’s Thread Model. Mostly not Thread Safe by design - very few thread safe operations All events added to AWT Queue and processed sequentially
E N D
Keeping your Swing Applications Responsive using FoxTrotand Friends Rob Ratcliff
Swing’s Thread Model • Mostly not Thread Safe by design - very few thread safe operations • All events added to AWT Queue and processed sequentially • Events “popped” off queue by dispatcher running in AWT Thread and delivered to registered listeners • Long running listener code results in a non-responsive application
Consequences of direct Swing calls in an alternate thread • Deadlock • Quirky Painting • Sluggish application
Alternatives – Worker Thread and InvokeLater() // some swing code new Thread(new Runnable() { public void run() { // long running task runSwingCode(); } protected void runSwingCode() { SwingUtilities.invokeLater(new Runnable(){ public void run() { // run more swing code } } } ).start();
Alternatives – SwingWorker // some swing code new SwingWorker() { public Object construct() { // long running code } public void finished() { // more swing code } }.start();
JDialog’s Approach • Modal dialog blocks AWT Event Thread • Creates another thread to dispatch the events to keep the GUI painting • FoxTrot leverages this concept
FoxTrot Approach • Similar to JDialog • Blocking call, but takes over event queue processing • Natural • Usage: // some swing code try { Object value = Worker.post(new Task() { public Object run() throws Exception { // long running task }}); } catch (Exception e) {// do something} // more swing code
Dynamic Proxy Client • Wrap long running calls a Dynamic Proxy that wraps calls with Foxtrot • Avoid sprinkling Foxtrot calls everywhere • Assists developers in not having to worry about this stuff • Keep this stuff deep down in your framework
Comments on Dynamic Proxy for CallBacks • Example Problem – RMI Callback • Callback calls Swing methods on RMI dispatch thread to update GUI • Inevitable that invokeLater() will be forgotten by some developer on team resulting in an embarassing deadlock! • Embed InvokeLater into a proxy around the callback interface (See ChatListenerNotifierFactory.)
References • Foxtrot - http://foxtrot.sourceforge.net/ • Simone Bordet - simone.bordet@hp.com • SwingWorker -http://java.sun.com/products/jfc/tsc/articles/threads/update.html • Threads and Swing - http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html • Dyanamic Proxy -