Last active
September 5, 2018 09:51
-
-
Save sonOfRa/5babf2ad81a100a128420529eb7693a0 to your computer and use it in GitHub Desktop.
Scope-Based locking in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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