Skip to content

Instantly share code, notes, and snippets.

@sonOfRa
Last active September 5, 2018 09:51
Show Gist options
  • Select an option

  • Save sonOfRa/5babf2ad81a100a128420529eb7693a0 to your computer and use it in GitHub Desktop.

Select an option

Save sonOfRa/5babf2ad81a100a128420529eb7693a0 to your computer and use it in GitHub Desktop.
Scope-Based locking in Java
import java.util.concurrent.locks.Lock;
/**
* Lock Guarding class similar to C++ lock_guard. Acquires
* the lock on construction and releases it on close().
*/
public class LockGuard implements AutoCloseable {
private final Lock l;
public LockGuard(Lock l) {
l.lock();
this.l = l;
}
@Override
public void close() {
this.l.unlock();
}
}
import java.util.concurrent.locks.ReentrantLock;
public class Usage {
public static void main(String[] args) {
ReentrantLock l = new ReentrantLock();
// Creating a new LockGuard instances acquires the lock
try (LockGuard guard = new LockGuard(l)) {
System.out.println(l.isHeldByCurrentThread());
}
// Here the lock is no longer held because the guard was closed
System.out.println(l.isHeldByCurrentThread());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment