我发现使用 ReentrantLock 而不是同步的另一个好处
下面的代码显示即使在临界区锁被释放时发生异常(使用 ReentrantLock )
void someMethod() {
//get the lock before processing critical section.
lock.lock();
try
{
// critical section
//if exception occurs
}
finally
{
//releasing the lock so that other threads can get notifies
lock.unlock();
}
}//end of method
现在通过使用同步
void someMethod() {
//get the lock before processing critical section.
synchronized(this)
{
try
{
// critical section
//if exception occurs
}
finally
{
//I don't know how to release lock
}
}
}//end of method
通过比较这两个代码,我发现使用同步块还有一个缺点,即如果在关键部分发生异常,则无法释放锁。
我对吗 ?
如果我错了,请纠正我。
如果同步块中发生异常,是否有释放锁?