Surprisingly, this question has no satisfactory answer. A safe usage of a LockCloseable would be liketry (LockCloseable lockCloseable = LockCloseable.lock(lock)) {    doSomethingUnderLock();} // automatic releaseor using @lombok.Cleanup{    @Cleanup LockCloseable lockCloseable = LockCloseable.lock(lock)    doSomethingUnderLock();} // automatic release when the scope is leftwhile all answers either create a new lock (non-sense) or when locking return an existing object (dangerous) or return void (unusable with try-with resources).So I'm giving it a try:@RequiredArgsConstructor(access=AccessLevel.PRIVATE)public final class MgLockCloseable implements AutoCloseable {    public static MgLockCloseable tryLock(Lock lock) {        return new MgLockCloseable(lock.tryLock() ? lock : null);    }    public static MgLockCloseable lock(Lock lock) {        lock.lock();        return new MgLockCloseable(lock);    }    @Override public void close() {        if (isLocked()) {            lock.unlock();        }    }    public boolean isLocked() {        return lock != null;    }    @Nullable private final Lock lock;}Notes:RequiredArgsConstructor comes from lombok and does exactly what the name says.I implemented only the two methods I need.It's only AutoCloseable as the closing is not idempotent.
AutoCloseable Lock
java;locking;lombok