Groovy Goodness – ReadWriteLocks
We often use synchronization. Imagine you have a use case in which there is some resource upon which writing is not done as much as compared to reading. So multiple threads should be able to read concurrently same resource without any problems. But if a single thread wants to write to the resource, for that all new threads for reading should be blocked or allowed to finish execution if already in reading process.
In other words while writing no other threads should be able read or write, this can be achieved using read / write lock. In Java one can use an implementation of ReadWriteLock interface in java.util.concurrent.locks package which provides readLock and writeLock objects to achieve this.
Groovy has provided two annotations for above use which are simply wrapper of ReentrantReadWriteLock
– groovy.transform.WithReadLock
– groovy.transform.WithWriteLock
import groovy.transform.*;
We will see an example to understand. So below getResource() method is not blocked until any thread is accessing any of updateAndGetResource() and refresh() methods and vice versa.
[java]
public class ResourceProvider {
private final Map<String, Object> data = new HashMap<String, Object>();
@WithReadLock
public String getResource(String key) throws Exception {
return data.get(key);
}
@WithWriteLock
public void refresh() throws Exception {
//reload the resources into memory
}
@WithWriteLock
public String updateAndGetResource(String key){
refresh()
//updating the shared resource for some special key
getResource(key)
}
//no blocking required
public void update(String key){
Object object = data.get(key)
//now update object mutable attributes
}
}
[/java]
Now you can use synchronization much more efficiently with read/write locks.
Hope this helps!!!
Parampreet Singh
Please explain why update method doesn’t require locking?
It does updates/writes (as name suggests).