Skip to content

Instantly share code, notes, and snippets.

@pablomoretti
Created December 22, 2013 20:54
Show Gist options
  • Save pablomoretti/8088328 to your computer and use it in GitHub Desktop.
Save pablomoretti/8088328 to your computer and use it in GitHub Desktop.
Get lock by name using java.util.concurrent
package com.mercadolibre.concurrent;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
public class LockByName<L> {
ConcurrentHashMap<String, L> mapStringLock;
public LockByName(){
mapStringLock = new ConcurrentHashMap<String, L>();
}
public LockByName(ConcurrentHashMap<String, L> mapStringLock){
this.mapStringLock = mapStringLock;
}
@SuppressWarnings("unchecked")
public L getLock(String key) {
L initValue = (L) createIntanceLock();
L lock = mapStringLock.putIfAbsent(key, initValue);
if (lock == null) {
lock = initValue;
}
return lock;
}
protected Object createIntanceLock() {
return new ReentrantLock();
}
public static void main(String[] args) {
LockByName<ReentrantLock> reentrantLocker = new LockByName<ReentrantLock>();
ReentrantLock reentrantLock1 = reentrantLocker.getLock("pepe");
try {
reentrantLock1.lock();
//DO WORK
}finally{
reentrantLock1.unlock();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment