简体   繁体   中英

Reentrant lock releases automatically in java

Is there any way can we release the re entrant lock automatically.does not need to unlock in finally block is there any way to achieve this

try{
lock.lock;

}
catch(Exception e){

lock.unlock

}

It can be done with an annotation but using the AutoCloseable is also an option:

import java.util.concurrent.locks.ReentrantLock;

public class LockTry {

public static void main(String[] args) {

    new LockTry().testWithLock();
}

private void testWithLock() {

    ReentrantLock lock = new ReentrantLock();
    try (CloseableLock clock = new CloseableLock(lock)) {
        System.out.println("run with lock");
    }
}

static class CloseableLock implements AutoCloseable {

    private final ReentrantLock lock;

    CloseableLock(ReentrantLock lock) {
        super();
        this.lock = lock;
        lock.lock();
        System.out.println("locked");
    }

    @Override
    public void close() {
        lock.unlock();
        System.out.println("unlocked");
    }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM