Over a million developers have joined DZone.

Swing Tip : A Better SwingWorker Without Exception Swallowing

· Java Zone

The Java Zone is brought to you by Stormpath—offering a pre-built Identity API for developers. On 11/3 at 10AM PT, join Stormpath Developer Evangelist, Micah Silverman, to dive deep into using JWTs to protect microservices from CSRF and more. Register here!

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/

Building Identity Management, including authentication and authorization? Try Stormpath! Our REST API and robust Java SDK support can eliminate your security risk and can be implemented in minutes. Sign up, and never build auth again!


The best of DZone straight to your inbox.

Please provide a valid email address.

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 }}