A Lock is always followed by a try/finally block, why?
ReentrantReadWriteLock readWriteLockBitmap = new ReentrantReadWriteLock();
Lock read = readWriteLockBitmap.readLock();
Lock write = readWriteLockBitmap.writeLock();
int shared = 0;
public void function1(){
read.lock();
try{
//reading shared int
}
finally{
read.unlock();
}
}
public void function 2(){
write.lock();
try{
//modify shared int
}
finally{
write.unlock();
}
}
Why having this try/finally block and not simply writing the code as follows:
ReentrantReadWriteLock readWriteLockBitmap = new ReentrantReadWriteLock();
Lock read = readWriteLockBitmap.readLock();
Lock write = readWriteLockBitmap.writeLock();
int shared = 0;
public void function1(){
read.lock();
//reading shared int
read.unlock();
}
public void function 2(){
write.lock();
//modify shared int
write.unlock();
}
In case anything goes wrong (Exception being thrown etc.) you want to make sure the lock is released no matter what. It’s just standard practice, even though in this case may technically be unnecessary.