Thursday, September 25, 2008

Hamlet D'Arcy's "Declarative Synchronization with Java 5's ReadWriteLock"

Hamlet D'Arcy posts on declarative synchronization with Java combining JDK4 proxies, JDK5 concurrency and Groovy, a very slick conjunction of technologies. Plus Hamlet is a cool name.

UPDATE: It is simple enough to translate the Groovy into pure Java (with a class rename and factory method along the way):

public class ReentrantHandler
        implements InvocationHandler {
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    private final Object target;

    public static <T> T newReentrantProxy(final Class<T> itf, final T impl) {
        return itf.cast(newProxyInstance(impl.getClass().getClassLoader(),
                new Class<?>[]{itf}, new ReentrantHandler(impl)));
    }

    private ReentrantHandler(final Object target) {
        this.target = target;
    }

    public Object invoke(final Object proxy, final Method method,
            final Object[] args) {
        try {
            final Method targetMethod = target.getClass().getMethod(
                    method.getName(), method.getParameterTypes());

            if (targetMethod.isAnnotationPresent(WithReadLock.class)) {
                lock.readLock().lock();
                try {
                    return targetMethod.invoke(target, args);
                } finally {
                    lock.readLock().unlock();
                }
            } else if (targetMethod.isAnnotationPresent(WithWriteLock.class)) {
                lock.writeLock().lock();
                try {
                    return targetMethod.invoke(target, args);
                } finally {
                    lock.writeLock().unlock();
                }
            } else {
                return targetMethod.invoke(target, args);
            }
        } catch (final Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

2 comments:

Hamlet D'Arcy said...

Are you using this in production? What do you think of this approach from a maintenance point of view? My worry is that it hides too much from the programmer and might be difficult to reason about later.

Brian Oxley said...

I am not using in production, no. :) More of a gedanken post. Thanks for asking!