bad.robot

good robots do what they're told

Wrapping Exceptions is Dull

I’m totally bored of wrapping exceptions in Java,

try {
   // do something
} catch (BoredomException e) {
   // do something else
}

It’s verbose, ugly and has nothing to do with what you’re really trying to convey. It’s just noise. For example, when using the dreadful Google Data API to access my calendar, I wrapped a couple of underlying Google services to be able to mock. Each service wanted to throw a bunch of Google specific exceptions which I wanted to rethrow as application specific exceptions.

public O call() throws CalendarException {
    try {
        return service.call();  // the call to the google service
    } catch (MalformedURLException e) {
        throw new CalendarException(BAD_URL_MESSAGE, e);
    } catch (IOException e) {
        throw new CalendarException(IO_EXCEPTION_MESSAGE, e);
    } catch (AuthenticationException e) {
        throw new CalendarException(AUTHENTICATION_MESSAGE, e);
    } catch (ServiceException e) {
        throw new CalendarException(SERVICE_EXCEPTION_MESSAGE, e);
    }
}

If I didn’t delegate like this, every internal call would have to wrap and handle the google exceptions rather than my application specific one. There’s no class hierarchy in Google’s API here.

As I’ve done this a few times, I decided to add it to tempus-fugit as a ExceptionWrapper class. Using this class, you can wrap a Callable to rethrow any caught exception as some other (including the underlying exception as the cause).

So, in a similar way to the above, the client can ignore any declared exceptions and just rethrow them in-line. For example,

wrapAnyException(new Callable<Object>() {
    @Override
    public Object call() throws ServiceException {
         // nasty code throwing a bunch of exceptions
    }
}, with(CalendarException.class));

when this is in-lined further, it hopefully becomes more succinct.

wrapAnyException(serviceCall(), with(CalendarException.class));

This will wrap any exception and rethrow as a new CalendarException to include as the cause any underlying exception. It uses reflection to create the new exception, and forces the syntactically sugary with by taking a WithException as the second parameter.

It’s in tempus-fugit, let me know if you find it useful.

Nibbles the Cat & Concurrency

I recently introduced a deadlock into our performance monitoring. I inadvertently prevented a statistic collection daemon I wrote from shutting down thanks to some unlucky timing and a bad synchronisation policy. Because the synchronisation that was involved was distributed across a couple of classes (including some external classes) it wasn’t obvious where they clashed. It got me thinking more about deadlocks and how many times we actually see them in real systems. In the end, I created a DeadlockDetector class.

I’m talking here about Java level deadlocks and to illustrate the point, poor old Nibbles got himself into quite a pickle. The situation is like this; Nibbles has been abducted and the Kidnapper and Negotiator threads have started a dialogue.

public void potentialDeadlock() {
     new Kidnapper().start();
     new Negotiator().start();
}

However, in the process of negotiation it becomes apparent that the Kidnapper is unwilling to release poor Nibbles until he has received the Cash and the Negotiator is unwilling to part with the Cash until he has poor Nibbles back in his arms.

Type Safe Annotation

A new year and another Java gripe! This time its annotations and the lack of anything useful by way of parameters. Implementing the Goetz annotations from Concurrency In Practice, I wanted to include an enum as a parameter type. Kind of like this

public @interface GuardedBy {
   Type value();

   public enum Type { FIELD, CLASS; }
}

Running JUnit tests in parallel

I’ve been playing with running tests in their own threads for a while now (in particular with reference to GUI testing) and am starting to feel comfortable with my approach. Today I was working on running tests in parallel with JUnit.

Flickering Tests and a JUnit Rule

Occasionally I’ll see flickering tests. Sometimes they’re green, sometimes they’re red and this can happen without any code changes. What bugs me the most is that when trying to fix the problem, I can never be sure that I haven’t just been lucky and the green I’m seeing isn’t really a false positive. I’ll have to manually run the test several times before my confidence grows.

In an attempt to ease the situation, I created an @Intermittent annotation with a corresponding JUnit Rule and Runner. Now, I can mark up a suspect test and get JUnit to do the repetition. Joy.

@Test
@Intermittent
public void flickering() {
   // ...
}

You can then use the IntermittentRule to run the test method repeatedly.

public class FlickeringTest {

    @Rule public IntermittentRule rule = new IntermittentRule();

    @Test
    @Intermittent
    public void flickering() {
        // ...
    }
}

Or use the @RunWith annotation to run the test using the IntermittentTestRunner.

@RunWith(IntermittentTestRunner.class)
public class FlickeringTest {

    @Rule public IntermittentRule rule = new IntermittentRule();

    @Test
    @Intermittent
    public void flickering() {
        // ...
    }
}

What’s interesting here is the way in which the Rule and Runner interact with JUnit. Newer versions of JUnit have introduced the idea of Rules and Statements. Using a Rule allows access to the underlying Statement which in our case is the action to run the test method. So we’re able to run the underlying statement again and again. Nice.

The Runner however can hook into JUnit’s framework in a different way. It can access more than one statement and so can position itself slightly differently. What this means for us is that when using the Rule above, any @Before or @After methods will only be run once but the test method will run multiple times. Using the Runner above however, will run any @Before or @After methods once for each test repetition.

The code is available as part of the tempus-fugit library, feel free to look around.

Deadlock detection in Java

I recently added a basic deadlock detection mechanism to tempus-fugit. The DeadlockDetector class allows you to programmatically detect basic deadlocks in your Java code. You can output deadlocks using the following code (note that printing a thread dump using the ThreadDump class will automatically attempt to find any deadlocks).

DeadlockDetector.printDeadlocks(System.out);

Atomiticy of the Thread class

I had an interesting time getting a couple of tests running for tempus-fugit recently. It threw up a couple of interesting aspects about using threads that I hadn’t come across before.

In one particular test, I wanted to show that interrupt is called on a thread and so followed what’s becoming a common pattern for me.

@Test
public void sleepInterrupted() throws Exception {
   Thread thread = threadSleepsForever();
   thread.start();
   waitForStartup(thread);
   thread.interrupt();
   waitForShutdown(thread);
   assertThat(thread.isInterrupted(), is(true));
}

The alternative patten is to wait for the assertion and avoid the wait for shutdown method above. Either way, the test above is testing that the thread created has been interrupted by checking the interrupt flag.

The test was failing for me even though I was able to show that the interrupt is called and the interrupt flag is set immediately after the sleeping thread is woken. However, when the test reached the assertion, it was false. Weird.

Time Flies 1.0

I’ve just published tempus-fugit 1.0-SNAPSHOT to maven central repository.

oh, I should mention… tempus-fugit represents two things to me

  1. A focal point to a lot of head scratching around the theme of testing concurrency and time sensitive code.
  2. An attempt to consolidate this thinking into a single place that can be easily reused.

What it actually is, is

  1. a dozen or so classes that capture key abstractions we’ve found are frequently shared across domains.
  2. an even smaller number of wrapper or helper classes that we’ve found can help using concurrency in Java that little bit nicer.
  3. all with an underlying theme of testing and improving testability.

Thawte claim I’m not to be trusted…

…well, not quite, but they have recently announced that they’d be discontinuing the Personal E-mail Certificates and Web of Trust. These were free services and it comes as bit of a blow as I’ve been using them to sign my JARs for WebStart deployment. As Thawte are a root authority, it meant no annoying prompts from WebStart claiming I was a would-be terrorist. Looks like I’m back to hiding in shadows.

A couple of useful links below.

Performance Monitoring Basics

Keeping an eye on the performance of your applications is something that it easy to neglect. We all know that we should be regularly recording key performance indicators and regularly leaning on the profiler to spot dangers early, but how often is the dust actually blown off?

I’ve been doing a fair bit of performance monitoring work lately and thought it might be a good idea to capture a few thoughts.