當延遲稍高時,一個簡單的片段經常卡住:
public String getToken(String userId, ReentrantLock lock) throws InterruptedException {
try {
// lock is in a cache of ConcurrentHashMap with key of userId
if (!lock.tryLock(LOCK_TIMEOUT_SEC, TimeUnit.SECONDS)) {
throw new AppException("Could not get lock in " LOCK_TIMEOUT_SEC "s"); // 10 sec
}
String token = fetchNewToken(userId); // call external endpoint
lock.unlock();
return token;
} finally {
while (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
現在的情況是,當fetchNewToken延遲稍高(如 1 秒)并引發很多例外時,它通常會鎖定 10 秒。以前它無需檢查即可解鎖,我更改了 finally 部分,但現在我不確定。
我應該檢查 finally 塊中的鎖所有者嗎?如果其他執行緒都持有它,我想我應該不解鎖?
我發現的示例從不檢查所有者。所以懷疑。
uj5u.com熱心網友回復:
如果其他執行緒都持有它,我想我應該不解鎖?
當然不。
你把它復雜化了。除非你知道你已經獲得它,否則不要解鎖。移動 try-finally 塊。您也不需要 2 次通話即可解鎖。finally 塊將適用于所有情況;這就是它存在的原因。
public String getToken(String userId, ReentrantLock lock) throws InterruptedException {
// lock is in a cache of ConcurrentHashMap with key of userId
if (!lock.tryLock(LOCK_TIMEOUT_SEC, TimeUnit.SECONDS)) {
throw new AppException("Could not get lock in " LOCK_TIMEOUT_SEC "s"); // 10 sec
}
try {
return fetchNewToken(userId); // call external endpoint
} finally {
lock.unlock();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/521554.html
標籤:爪哇锁定
