tempus-fugit

Java micro-library for writing & testing concurrent code

Sleeping and Interruptions

Often, you'll see code like the example below

1
2
3
4
5
try {
   Thread.sleep(100);
} catch (InterruptedException e) {
   // nothing
}

tempus-fugit captures the annoying boiler plate code needed to reset the interrupt flat in situations where you can't or don't want to rethrow the InterruptedException.

Using the ThreadUtils.sleep method, the above code is rewritten as.

1
sleep(millis(100));

This ensures that the interrupt flag is reset and is more explicit about the duration of the sleep.

If you want to ensure the interrupt flag is reset for other code, you can use the ThreadUtils.resetInterruptFlagWhen method directly. The Interruptible interface is used to highlight that the lamda-like call you want to execute does in fact throw the InterruptedException. For example;

1
2
3
4
5
6
resetInterruptFlagWhen(new Interruptible<Void>() {
    public Void call() throws InterruptedException {
        Thread.sleep(100);
        return null;
    }
});

Extracting the lamda-like Interruptible to a method makes the code more expressive;

1
resetInterruptFlagWhen(sleepingIsInterrupted());

This is actually how the ThreadUtils.sleep method is implemented within tempus-fugit.

Next, Thread Utilities: Scheduled Interruption »