Java의 Autolock- 어떻게?
-
02-07-2019 - |
문제
스코프를 떠날 때 리소스를 자유롭게하는 가장 좋은 방법은 무엇입니까 (이 경우 readwritelock을 잠금 해제)? 가능한 모든 방법 (반품, 휴식, 예외 등)을 다루는 방법은 무엇입니까?
해결책
시도/마침내 블록은이 행동에 도달 할 수있는 가장 가까운 것입니다.
Lock l = new Lock();
l.lock(); // Call the lock before calling try.
try {
// Do some processing.
// All code must go in here including break, return etc.
return something;
} finally {
l.unlock();
}
다른 팁
Mike가 말했듯이, 마침내 블록이 당신의 선택이되어야합니다. 참조 마지막으로 튜토리얼을 차단하십시오, 그것이 언급 된 곳 :
마침내 블록 언제나 시도 블록이 종료 될 때 실행됩니다. 이렇게하면 예기치 않은 예외가 발생하더라도 최종 블록이 실행되도록합니다.
더 좋은 방법은 C ++를 모방 할 수있는 Try-With-Resources 문을 사용하는 것입니다. Raii 메커니즘:
public class MutexTests {
static class Autolock implements AutoCloseable {
Autolock(ReentrantLock lock) {
this.mLock = lock;
mLock.lock();
}
@Override
public void close() {
mLock.unlock();
}
private final ReentrantLock mLock;
}
public static void main(String[] args) throws InterruptedException {
final ReentrantLock lock = new ReentrantLock();
try (Autolock alock = new Autolock(lock)) {
// Whatever you need to do while you own the lock
}
// Here, you have already released the lock, regardless of exceptions
}
}
제휴하지 않습니다 StackOverflow