Posterous theme by Cory Watilo

Groovy goodness: force synchronized access to non-synchronized method with metaprogramming

Say you’ve got a singleton instance of some class to which you’d like to enforce synchronized access. No need for sub-classing, proxies or related tomfoolery with Groovy: just hack that metaclass!

Enforce synchronized access to all methods of a single instance
def resource = FactoryClass.getSingleton()
def lock = new ReentrantLock()
resource.metaClass.invokeMethod = { String name, args ->
    def result
    def metaMethod = delegate.metaClass.getMetaMethod(name, args)
    if (metaMethod) {
        lock.lock()
        try { result = metaMethod.doMethodInvoke(delegate, args) }
        finally { lock.unlock() }
    } else {
        throw new MissingMethodException(name, delegate.class, args)
    }
    return result
}

// ... and later, from multiple threads ...
resource.doSomething() // <- call will be synchronized