同期よりも ReentrantLock を使用する利点がもう 1 つあります。
以下のコードは、クリティカルセクションで例外が発生してもロックが解除されることを示しています ( 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
両方のコードを比較すると、同期ブロックを使用することにはもう1つの欠点があることがわかります。つまり、クリティカルセクションで例外が発生した場合、ロックを解放できないことです。
私は正しいですか?
間違っている場合は修正してください。
同期ブロックで例外が発生した場合、ロックを解除する方法はありますか?