tempus-fugit

Java micro-library for writing & testing concurrent code

Always Execute Using Locks

Using implementations of the java.util.concurrent.locks.Lock requires that the lock is acquired and released after use. This leads to the common idiom below.

1
2
3
4
5
6
7
Lock lock = new ReentrantLock();
lock.lock;
try {
   // something useful
} finally {
    lock.unlock();
}

The ExecuteUsingLock class provides a way to abstract the lock acquisition and release and ensure consistency across your code. It takes a Callable representing the statements to execute whilst the lock is acquired and the actual lock to use when executing and ensures the lock is always released.

1
2
3
4
5
6
7
8
9
10
11
public void forExample {
    execute(something()).using(lock);
}

private Callable<Void, RuntimeException> something() {
    return new Callable<Void, RuntimeException>() {
        public Void call() throws RuntimeException {
            return null;
        }
    };
}

Next, Concurrency Utilities: Timeoutable Completion Service »