Almost every java developer knows about synchronizing methods or code blocks using synchronized keyword, but very few knows abut synchronizing using Reentrant locks.
Before moving on to code samples directly, I would strongly suggest you to read the java doc for Reentrant lock :
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html
You will be already impressed by the number of utility methods provided by the lock, and how it helps in making a multi threaded application development easier.
Now lets move on to one of the simplest use case of using re-entrant lock , ie, implementing synchronized methods using re entrant locks.
This is how a synchronized method looks like :
private void synchronized setValue(int myValue) {
//setting a value for concurrent hashset
value = value + myValue;
}
The same can be achieved using a re-entrantlock as follows :
//define a reentrant lock as follows :
final Lock valueLock = new ReentrantLock();
private void setValue(int myValue) {
try {
if (valueLock .tryLock(10, TimeUnit.SECONDS)) {
value = value + myValue;
}
} catch (InterruptedException e) {
log.error("Exception while acquiring the lock!! ");
} finally {
valueLock .unlock();
}
}
Before moving on to code samples directly, I would strongly suggest you to read the java doc for Reentrant lock :
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html
You will be already impressed by the number of utility methods provided by the lock, and how it helps in making a multi threaded application development easier.
Now lets move on to one of the simplest use case of using re-entrant lock , ie, implementing synchronized methods using re entrant locks.
This is how a synchronized method looks like :
private void synchronized setValue(int myValue) {
//setting a value for concurrent hashset
value = value + myValue;
}
The same can be achieved using a re-entrantlock as follows :
//define a reentrant lock as follows :
final Lock valueLock = new ReentrantLock();
private void setValue(int myValue) {
try {
if (valueLock .tryLock(10, TimeUnit.SECONDS)) {
value = value + myValue;
}
} catch (InterruptedException e) {
log.error("Exception while acquiring the lock!! ");
} finally {
valueLock .unlock();
}
}
No comments:
Post a Comment