Skip to content

Instantly share code, notes, and snippets.

@mandykoh
Created May 13, 2013 20:49
Show Gist options
  • Select an option

  • Save mandykoh/5571402 to your computer and use it in GitHub Desktop.

Select an option

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.
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