Created
December 22, 2013 20:54
-
-
Save pablomoretti/8088328 to your computer and use it in GitHub Desktop.
Get lock by name using java.util.concurrent
This file contains 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
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