AutoLock en Java - comment faire?
-
02-07-2019 - |
Question
Quel est le meilleur moyen de libérer des ressources (dans ce cas, déverrouillez le ReadWriteLock) lorsque vous quittez l’étendue? Comment couvrir tous les moyens possibles (retour, pause, exceptions, etc.)?
La solution
Un bloc try / finally est ce que vous pouvez obtenir de plus près à ce comportement:
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();
}
Autres conseils
Comme l’a dit Mike, un choix final devrait être votre choix. voir le bloquer définitivement le didacticiel , où il est indiqué :
Le bloc finally toujours est exécuté lorsque le bloc try se termine. Cela garantit que le bloc enfin est exécuté même si une exception inattendue se produit.
Une méthode plus pratique consiste à utiliser l'instruction try-with-resources, qui vous permet de simuler le comportement de C ++ Mécanisme 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
}
}