[英]How to properly scope a lock
Let's say I have a ReentrantLock
, 假设我有一个
ReentrantLock
,
ReentrantLock foo = new ReentrantLock();
and a method bar
that uses the lock, 以及使用锁的方法
bar
,
public void bar()
{
foo.lock();
try
{
methodOne();
}
finally
{
foo.unlock();
}
}
and methodOne
calls a method methodTwo
that also uses the lock, 和
methodOne
调用一个方法methodTwo
同样使用该锁,
public void methodTwo()
{
foo.lock();
try
{
// do something
}
finally
{
foo.unlock();
}
}
is it better to release the lock in bar
before I call methodOne
? 是它更好地释放锁在
bar
前我打电话methodOne
? In general, is it good practice to release the lock before calling another method? 通常,在调用另一个方法之前释放锁是一种好习惯吗?
No, you should not do that. 不,您不应该那样做。 If you do it, any concurrent thread could acquire the lock in the middle of the
bar()
method, which is precisely what you want to avoid by using a lock. 如果这样做,任何并发线程都可以在
bar()
方法的中间获取锁,这正是您希望通过使用锁来避免的锁。
It's called ReentrantLock precisely because it allows acquiring the lock multiple times in the same thread. 确切地说,它被称为ReentrantLock,因为它允许在同一线程中多次获取锁。 A counter is incremented each time
lock()
is called, and decremented each time unlock()
is called, so you just need to make sure unlock()
is always called in a finally block. 每次调用
lock()
时,计数器都会递增,而每次调用unlock()
时,计数器都会递减,因此您只需要确保在finally块中始终调用unlock()
。
Note that the code would be less fragile by simply using synchronized blocks, because it's impossible to forget closing a synchronized block. 请注意,仅通过使用同步块,代码就不会那么脆弱,因为不可能忘记关闭同步块。
Release the lock when the critical operations the lock "protects" are done. 完成锁“保护”的关键操作后,松开锁。 No sooner.
不早于。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.