Skip to content

Instantly share code, notes, and snippets.

@amitnarayanan
Created March 5, 2016 18:24
Show Gist options
  • Save amitnarayanan/be9ea127dcb3cd8b1156 to your computer and use it in GitHub Desktop.
Save amitnarayanan/be9ea127dcb3cd8b1156 to your computer and use it in GitHub Desktop.
A simple striped lock
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.Lock;
/**
* Striped lock impl for when proper concurrency libs (like guava) can't be used, either due to
* dependency issues or other reasons.
*
* Returns (creates if not exists) a unique Lock for a given K
*
* @author Amit Narayanan
*/
public class StripedLock<K, L extends Lock>
{
private ConcurrentMap<K, L> locks = new ConcurrentHashMap<K, L>();
/**
* For when creation of lock entails a simple new operator
*/
public L getOrCreateLock(K key, Class<? extends L> lockClass) throws Exception
{
final L lock = lockClass.newInstance();
return getLock(key, lock);
}
/**
* For when creation of lock is more involved (say requires Conditions, or other custom stuff).
*/
public L getOrCreateLock(K key, Callable<? extends L> lockCtor) throws Exception
{
final L lock = lockCtor.call();
return getLock(key, lock);
}
private L getLock(final K key, final L newLock)
{
L lock = locks.putIfAbsent(key, newLock);
return lock != null ? lock : newLock;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment