Monday 4 February 2013

Java 7 lock guard.

I love the RAII idiom in C++. Sadly it was not possible to use it in Java before Java 7 introduces the "try with resources" statement. Here is a simple example of how to use it to create a lock guard.
/**
 * Class used to acquire and release a lock as a ressource.
 * @author Simon
 */
public class LockGuard implements AutoCloseable {
    private Lock lock_;
    
    public LockGuard(Lock lock) {
        lock_ = lock;
        lock_.lock();
    }

    @Override
    public void close() {
        lock_.unlock();
    }
}

As you can see it is really straightforward. You acquire the lock in the constructor and release it in the close method. It is even easier to use it:
try (LockGuard guard = new LockGuard(lock)){ // Acquire the lock.
    // Access the resource protected by this lock.
    // Can safely throw.
} // Release the lock.
The only thing to do is using the LockGuard in a try with resource. You should never have to explicitly unlock any lock. This is not as nice as the C++ way because this requires a try block but no language is perfect...