Interruptible: To be or not to be

At the moment I’m working on the last issues for a first release of my concurrency library (called Prometheus). One of the things that annoyed me, were the large amount of methods that only differ in being or not being interruptible. Most blocking methods in this library had the following form:

E foo() throws InterruptibleEx;

E fooUninterruptibly();

And in most cases timed versions are also needed (untimed versions or more likely to cause deadlocks and other liveness problems):

E tryFoo(long timeout, TimeUnit unit)throws InterruptibleEx, TimeoutEx;

E tryFooUninterruptibly(long timeout, TimeUnit unit)throws TimeoutEx;

So for every blocking action there were 4 different variations, and this caused a lot of repetition in tests, implementation and documentation. Another consequence is that a library gets more complicated to use because there are a lot of alternatives to choose from, even though in 99% of the cases it is better to use one of the interruptible versions. Making a call uninterruptible maybe feels good because you don’t have to deal with the checked InterruptedException anymore. But it also prevents a blocking thread from being interrupted and this this could lead to other problems like a ThreadPoolExecutor that doesn’t shut down when the ThreadPoolExecutor.shutdownNow() is called.

One of the problems I had in the beginning while implementing uninterruptible timed methods, is that the Condition has no uninterruptible timed wait method. That is why I added an implementation to my library. I finally posted a question on the concurrency mailing list why this method was missing. David Holmes (one of the guys behind JSR-166 and one of the authors of ‘Java Concurrency in Practice’) replied that there was a reason why that method was missing:

If you are able to deal with a timeout, you probably are able
to deal with an interrupt as well.

Uninterruptible blocking methods

This started me thinking. First of all, it would be nice if I could drop most uninterruptible methods, because you don’t want to use them in most cases anyway. Only in cases where an InterruptedException leaves the system in an inconsistent state, an uninterruptible version is a better alternative. I was walking to my work, and it finally occurred to me: dealing with an interruptible section doesn’t have to be added to all components because it could be something ‘reusable’, example:

E fooUninterruptible(){
	UninterruptibleSection<E> section = new UinterruptibleSection<E>(){
		E originalsection()throws InterruptedEx{
			//interruptible call
			return fooObject.foo();
		}
	};
	section.execute();
}

The fooUninterruptibly is an uninterruptible version of the interruptible foo method. The UninterruptibleSection is responsible for dealing with the InterruptedException that is thrown by the original section of code. So whenever an uninterruptible version is needed, just wrap it in an UninterruptibleSection.

For those that are interested, this is the implementation of the UninterruptibleSection:

public abstract class UninterruptibleSection<E> {

    protected abstract E originalsection() throws InterruptedEx;

    public E execute() {
        boolean restoreInterrupt = Thread.interrupted();
        try {
            while (true) {
                try {
                    return originalsection();
                } catch (InterruptedException ex) {
                    restoreInterrupt = true;
                }
            }
        } finally {
            if (restoreInterrupt)
                Thread.currentThread().interrupt();
        }
    }
}

(Thanks David for pointing out the assertion failure).

Uninterruptible timed blocking methods

For timed calls I created a similar version, so that you get the same behavior as with the UninterruptibleSection. The main difference is that the timeout is taken into account, but other than that it works just the same. The question remains which one to choose, retrying until a timeout occurs (the behavior my solution provides), or failing immediately when a call is interrupted (the behavior David suggested). Personally I don’t know which one to choose because both of them make sense. In my case there is some chance that an action completes, and the solution David suggests, is more responsive to interrupts.

I refactored the code so it uses an UninterruptibleSection, the code for the uinterruptible timed-await for condition after refactoring looks like this:

public static long awaitNanosUninterruptibly(
	final Condition condition,
	long timeoutNs
	)throws TimeoutException {
    if (condition == null) throw new NullPointerException();

    TimedUninterruptibleSection<Long> section =
    	new TimedUninterruptibleSection<Long>() {

        protected Long originalsection(long timeoutNs)
                    throws InterruptedException, TimeoutException {
            timeoutNs = condition.awaitNanos(timeoutNs);
            if (timeoutNs <= 0)
                throw new TimeoutException();
            return timeoutNs;
        }
    };

    return section.tryExecute(timeoutNs, TimeUnit.NANOSECONDS);
}

Conclusion

With the addition of the UninterruptibleSection and the TimedUninterruptibleSection I was able to remove a lot of code and simplify the synchronization behavior of interfaces and classes without losing functionality. And with Java 7 and the closure support, the syntactic ugliness can even be softened.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: