Asserting SwingWorker

I have had a chance to play around with some java code recently for a change of pace and I was excited to use the new SwingWorker class in JSE6. However I also am in the habit of programming with asserts which I found out to be a problem if one triggers while running in a SwingWorker thread.

If you look at the base class of SwingWorker, FurtureTask, in the inner class Sync, which is where the actual task is run there is this method:

boolean innerRunAndReset() {
    if (!compareAndSetState(0, RUNNING))
        return false;
    try {
        runner = Thread.currentThread();
        if (getState() == RUNNING)
            callable.call(); // don't set result
        runner = null;
        return compareAndSetState(RUNNING, 0);
    } catch (Throwable ex) {
        innerSetException(ex);
        return false;
    }
}

The observant reader will notice that this code will catch all Throwables, which is the base class of Exception and Error, and an assert in java will throw a AssertError so your code will bomb out silently without notification if any Throwable is thrown.

try {
    // do threadded work here
} catch (AssertionError e) {
    logger
        .log(Level.WARNING,
        "Assertion while processing: {0}\n{1}",
        new Object[] { e.getMessage(),
        e.getStackTrace()[0] });
} catch (Exception e) {
    logger.log(Level.SEVERE,
        "Exception throw during processing {0}\n{1}",
        new Object[] { e.getClass().getName(),
        e.getMessage() });
    throw e;
} catch (Error e) {
    logger.log(Level.SEVERE,
        "Error throw during processing {0}\n{1}",
        new Object[] { e.getClass().getName(),
        e.getMessage() });
    throw e;
}

I use the a statically defined Logger, logger, to print output from the Exceptions and Errors.

This allows the thread to throw asserts but keep going and if it does bomb out on any other Error or Exception you get notified in your log making debugging a SwingWorker a bit easier.


Leave a Reply

:D :) :( :o 8) :eek: ;-( :grin: :wink: :arrow: :idea: :?: :!: :evil: O:) :-| :-* :-(( :poke: :love: :tired: :emotion: :party: :clown: :worried: X( :p