Over a million developers have joined DZone.

Swing Tip : A Better SwingWorker Without Exception Swallowing

DZone's Guide to

Swing Tip : A Better SwingWorker Without Exception Swallowing

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

When we develop Swing applications, SwingWorker are very helpful. But there is a big disadvantage using this class. if you don’t call get() in the done method, you will lose all the exceptions that the computation in the doInBackground() has thrown. And you action can stop and you will never see why. In 95% of my actions using SwingWorker, the doInBackground() return nothing.

Jonathan Giles has presented on his blog a good solution to solve this exception swallowing. In my side, I’ve often something to do in the EDT before the doInBackground() run, so I’ve made the changes on the code presented by Jonathan and it give me that simple class that I found better than the SwingWorker :

public abstract class BetterSwingWorker {
    private final SwingWorker<Void, Void> worker = new SimpleSwingWorker();
    public void execute() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
    protected void before() {
        //Nothing by default
    protected abstract void doInBackground() throws Exception;
    protected abstract void done();
    private class SimpleSwingWorker extends SwingWorker<Void, Void> {
        protected Void doInBackground() throws Exception {
            return null;
        protected void done() {
            try {
            } catch (final InterruptedException ex) {
                throw new RuntimeException(ex);
            } catch (final ExecutionException ex) {
                throw new RuntimeException(ex.getCause());

You can use as the default SwingWorker. You must implement the doInBackground() and done() methods and you can, only if you want, override the before() method that is invoked in the EDT at the start of the process. And then, you can execute your SwingWorker using execute().

I hope this little class can be useful to somebody.

Source for the non-swallowing swingworker.

From http://www.baptiste-wicht.com/2010/09/a-better-swingworker/

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}