Created
May 13, 2013 20:49
-
-
Save mandykoh/5571402 to your computer and use it in GitHub Desktop.
Class that provides a version of 'synchronized' which locks on a string value rather than an object instance.
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.HashMap; | |
| import java.util.Map; | |
| public class SymbolicLock | |
| { | |
| private final Map<String, LockEntry> lockEntries = new HashMap<String, LockEntry>(); | |
| public void synchronised(String key, Runnable runnable) | |
| { | |
| LockEntry lockEntry = acquireLockEntry(key); | |
| synchronized (lockEntry) { | |
| try { | |
| runnable.run(); | |
| } finally { | |
| lockEntry.release(); | |
| } | |
| } | |
| } | |
| private LockEntry acquireLockEntry(String key) | |
| { | |
| synchronized (lockEntries) { | |
| LockEntry lockEntry = lockEntries.get(key); | |
| if (lockEntry == null) { | |
| lockEntry = new LockEntry(key); | |
| lockEntries.put(key, lockEntry); | |
| } | |
| return lockEntry.acquire(); | |
| } | |
| } | |
| private class LockEntry | |
| { | |
| private final String key; | |
| private int references; | |
| private LockEntry(String key) | |
| { | |
| this.key = key; | |
| } | |
| public LockEntry acquire() | |
| { | |
| ++references; | |
| return this; | |
| } | |
| public void release() | |
| { | |
| synchronized (lockEntries) { | |
| if (--references == 0) | |
| lockEntries.remove(key); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment