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);
        }
    }
}
Post a Comment