Locks And Closures In Groovy

In a previous post, I wrote about using lambdas in Java to simplify the use of locks. I was able to get this up and running in Groovy.

I have the code for it at Github. I made a class called ClosureLock which has a method called “lockSomeCode” which takes a closure as the argument. It creates an instance of ReentrantLock, and calls the closure in a try/finally block. Now that I look at it, i suppose I should refactor it so the ReentrantLock is a private variable and can be re-used, since ClosureLock can be reused.

I also created a class called FirstLockRunner, which instantiates ClosureLock and uses it a few times.

After I figured this out, I did some googling, and a few other people have done this before. A guy named David Clark has a class called DemoLockEnhancements in a project called GroovyThreading.

A guy named Johannes Link also did something similar.

There are a couple of new Groovy books out. I think I will look them over in order to understand closures/lambdas better. I have been reading that lambdas can be used to improve concurrency in Java and are thread safe.

I know that the consensus is to move away from locks and instead use other concurrency techniques. But I think that if locks can be done cleanly and safely, then their use should be considered.

Image from Rudolf von Ems’ Chronicle of the World, a 14th century manuscript housed at Central Library of Zurich (Wikipedia page here). image from e-Codices, assumed to be allowed under Fair Use.