我们如何使用最后尝试Lock.lock和Lock.unlock [英] How would we use try finally for Lock.lock and Lock.unlock
问题描述
请考虑以下代码。为了在调用 listIterator
时阻止 IndexOutOfBoundsException
,我们使用读取器锁来检索基于索引的iteartor和writer锁否则在 stockCodes
上写操作时。
Consider the following code. In order to prevent IndexOutOfBoundsException
while calling listIterator
, we use a reader lock to retrieve the index based iteartor, and writer lock else where when write operation on stockCodes
.
请注意,我们没有使用任何锁定机制进行迭代使用 listIterator
,因为它来自 CopyOnWriteArrayList
。不需要锁定,因为不会抛出 ConcurrentModificationException
。
Take note that, we didn't use any locking mechanism to iterate using listIterator
, as it is from CopyOnWriteArrayList
. Locking is not required as ConcurrentModificationException
shall not be thrown.
// stockCodesReaderLock is reader lock from java.util.concurrent.locks.ReadWriteLock
// stockCodes is CopyOnWriteArrayList
// Acquire iterator in a safe way.
stockCodesReaderLock.lock();
final int stockCodesSize = stockCodes.size();
if (currIndex < stockCodesSize) {
listIterator = stockCodes.listIterator(currIndex);
}
stockCodesReaderLock.unlock();
我想知道,我是否应该尝试/终于
阻止,因为我看不出有任何异常出现的机会?如果使用 try / finally
是必须的,我应该使用(A)还是(B)?
I was wondering, whether I should have try/finally
block, as I cannot see any chance for exception to arise? If using try/finally
is a must, should I use (A) or (B)?
我有什么需要吗?
(A)
try {
stockCodesReaderLock.lock();
final int stockCodesSize = stockCodes.size();
if (currIndex < stockCodesSize) {
listIterator = stockCodes.listIterator(currIndex);
}
} finally {
stockCodesReaderLock.unlock();
}
(B )
stockCodesReaderLock.lock();
try {
final int stockCodesSize = stockCodes.size();
if (currIndex < stockCodesSize) {
listIterator = stockCodes.listIterator(currIndex);
}
} finally {
stockCodesReaderLock.unlock();
}
推荐答案
其他受访者是对的:你应该总是使用try / finally。
The other respondents are right: you should always use try/finally.
关于(A)或(B)是否正确,Sun似乎建议(B)in ReDrantReadWriteLock的JavaDoc (搜索终于看到它)。我想这是因为 lock()
方法如果失败就会抛出异常:例如,JavaDoc说它会抛出错误
在晦涩的情况下,同一个线程试图以递归方式获取锁定超过65535次。
Regarding whether (A) or (B) is correct, Sun seems to recommend (B) in the JavaDoc of ReentrantReadWriteLock (search for "finally" to see it). I suppose this is because the lock()
method could throw an exception if it fails: for example, the JavaDoc says it will throw an Error
in the obscure case where the same thread attempts to acquire the lock recursively more than 65535 times.
这篇关于我们如何使用最后尝试Lock.lock和Lock.unlock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!