Improve application performance with SwingWorker
I've put database queries right there in my GUI event handlers. I'm ashamed, very ashamed. I've seen a lot of code from others too, and I'm not alone in this mishandling of lengthy IO bound tasks. People sometimes actually perform web
POST operations from the EDT too. No kidding. You might even be involved, but I don't expect you to admit it.
You know what I'm talking about, right? I'm talking about the unresponsive, sluggish user interfaces that cause so many critics to believe that Java is so slow. Some of you (me too) have perhaps unknowingly contributed to their list of evidence.
If you've been intimidated by threads or if you've ever wondered how to fix all that messed up GUI event handling code that does way more than it should, you'll be pleased to know that Java SE 6 offers some relief. The
javax.swing.SwingWorker class makes it easy to fix those slow GUIs.
SwingWorker, you can move long-running, IO bound tasks away from the Swing event dispatch thread (EDT). The result is improved performance for your Swing applications. Snappy, responsive, quick GUIs; we all want those.
Imagine you have an application that responds to a button click by downloading an image. You might be tempted to put the image retrieval code right there in the event handler itself. If you're feeling good, maybe you refactor a bit, pulling that code into its own method, etc. However, it's still on the EDT. The result is that your UI can't respond to other events while its trekking out across the web. You'll notice the delay...nothing works on the GUI until the image finally arrives.
The figure below shows such a thread. During the time between points
B, the UI is unresponsive...it's busy downloading the image.
SwingWorker, you create a worker thread to do all the time-consuming work. The figure below shows how the time between points
B becomes significantly shorter, freeing the UI to respond to user events again.
Next week, I'm going to post a complete demo with source and tutorial information about how to use this class. I had a great time using
SwingWorker in queries to Flickr web services . The result is a fun demo that I'm positive you'll enjoy.