Pergunta

O que é a melhor maneira de recursos livres (neste caso desbloqueio do ReadWriteLock) ao sair do escopo? Como cobrir todas as formas possíveis (de retorno, ruptura, exceções, etc.)?

Foi útil?

Solução

Um try / finally bloco é a coisa mais próxima que você pode obter para este comportamento:

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();
}

Outras dicas

Como Mike disse, um bloco finally deve ser sua escolha. veja a finalmente bloquear tutorial , onde se afirma :

O bloco finally Sempre é executado quando as saídas do bloco try. Isso garante que bloco finally é executada mesmo que uma exceção inesperada.

A melhor maneira de se fazer isso é usar a instrução try-with-recursos, que permite imitar C ++ 's mecanismo de 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

    }

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top