This question already has answers here:
Notify not getting the thread out of wait state
(3 answers)
Closed 7 years ago.
Basically I have to create 3 classes (2 threaded).
First one holds some cargo (has a minimum capacity (0) and a maximum (200))
Second one supplies the cargo every 500ms.
Third one takes away from cargo every 500ms.
Main program has one cargo class(1), 2 supplier classes(2) and 2 substraction classes(3). Problem I'm having is that one by one, they're falling into a wait(); state and never get out. Eventually all of them get stucked in the wait() state, with the program running, but without them actually doing anything.
First class:
public class Storage {
private int maxCapacity;
private int currentCapacity;
public Storage( int currentCapacity, int maxCapacity ) {
this.currentCapacity = currentCapacity;
this.maxCapacity = maxCapacity;
}
public int getCapacity(){ return this.currentCapacity; }
public void increase( int q ) {
this.currentCapacity += q;
System.out.println("increase" + q + ". Total: " + currentCapacity);
}
public int getMax() { return this.maxCapacity; }
public void decrease( int q ) {
this.currentCapacity -= q;
System.out.println("decrease - " + q + ". Total: " + currentCapacity);
}
}
2nd class (supplier):
public class Supplier implements Runnable {
private int capacity;
private Storage storage;
private volatile boolean run;
public Supplier( int capacity, Storage storage ) {
this.capacity = capacity;
this.storage = storage;
this.run = true;
}
public void kiss_kill() { run = !run; }
public synchronized void add() {
while(storage.getCapacity() + capacity > storage.getMax()) {
try {
System.out.println("wait - supplier");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.increase(capacity);
notifyAll();
}
public void run() {
synchronized (this) {
while(run) {
add();
Thread.yield(); //would be wait(500), but this just speeds it up
}
}
}
}
3rd class (taker/demander):
public class Taker implements Runnable {
private int capacity;
private Storage storage;
private volatile boolean run;
public Taker( int capacity, Storage storage ) {
this.capacity = capacity;
this.storage = storage;
this.run = true;
}
public void kiss_kill() { run = !run; }
public synchronized void take() {
while(storage.getCapacity() - capacity < 0) {
try {
System.out.println("wait - taker");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.decrease(capacity);
notifyAll();
}
public void run() {
synchronized (this) {
while(run) {
take();
Thread.yield(); //again, wait(500) should be instead
}
}
}
}
Main is something like this:
public class Main{
public static void main(String... args) {
Storage sk = new Storage(100, 200);
Supplier[] s = { new Supplier(10, sk), new Supplier(15, sk) };
Taker[] p = { new Taker(15, sk), new Taker(20, sk) };
Thread t[] = {
new Thread(s[0]),
new Thread(s[1]),
new Thread(p[0]),
new Thread(p[1]) };
for(Thread th : t) th.start();
try {
Thread.sleep(60000); //program should last for 60s.
} catch (InterruptedException e) {
e.printStackTrace();
}
s[0].kiss_kill(); s[1].kiss_kill(); p[0].kiss_kill(); p[1].kiss_kill();
}
}
Why doesn't notifyAll() release the wait() state of other object? What could I do to fix this?
Sorry, I know it's a long example, I hate posting too many classes like this. Thanks for reading!
I translated the code, so if you spot anything that you're unsure about that I've missed, please tell me and I'll fix it right away!
Doing concurrency is easy:
Anyone can slap synchronized on methods and synchronized () {} around blocks of code. It does not mean it is correct. And then they can continue to slap synchronized on everything until it works until it doesn't.
Doing concurrency correctly is Hard:
You should lock on the data that needs to be consistent not the methods making the changes. And you have to use the same lock instance for everything.
In this case that is the currentCapacity in Storage. That is the only thing that is shared and the only thing that needs to be consistent.
What you are doing now is having the classes lock on instances of themselves which means nothing shared is being protected because there is no shared lock.
Think about it, if you are not locking on the same exact instance which must be final of an object then what are you protecting?
Also what about code that has access to the object that needs to be consistent and does not request a lock on it. Well it just does what it wants. synchronized() {} in calling classes is not how you protect shared data from external manipulation.
Thread safe objects are NOT about the synchronized keyword:
Read up on the java.util.concurrent package it has all the things you need already. Use the correct data structure for your use case.
In this particular case if you use AtomicInteger for your counter, you do not need any error prone manual locking, no need for synchronized anywhere, it is already thread safe.
Immutable Data:
If you work with immutable data exclusively you do not need any of this silly locking semantics that are extremely error prone for even those that understand it and even more so for those that think they understand it.
Here is a working idiomatic example:
This is a good chance to learn what non-deterministic means and how to use the step debugger in your IDE to debug concurrent programs.
Q33700412.java
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import com.vertigrated.FormattedRuntimeException;
public class Q33700412
{
public static void main(final String[] args)
{
final Storage s = new Storage(100);
final int ap = Runtime.getRuntime().availableProcessors();
final ExecutorService es = Executors.newFixedThreadPool(ap);
for (int i = 0; i < ap; i++)
{
es.execute(new Runnable()
{
final Random r = new Random();
#Override
public void run()
{
while (true)
{
/* this if/else block is NOT thread safe, I did this on purpose
the state can change between s.remainingCapacity() and
the call to s.increase/s.decrease.
This is ok, because the Storage object is internally consistent.
This thread might fail if this happens, this is the educational part.
*/
if (s.remainingCapacity() > 0)
{
if (r.nextBoolean()) { s.increase(r.nextInt(10)); }
else { s.decrease(10); }
System.out.format("Current Capacity is %d", s.getCurrentCapacity());
System.out.println();
}
else
{
System.out.format("Max Capacity %d Reached", s.getMaxCapacity());
System.out.println();
}
try { Thread.sleep(r.nextInt(5000)); }
catch (InterruptedException e) { throw new RuntimeException(e); }
}
}
});
}
es.shutdown();
try
{
Thread.sleep(TimeUnit.MINUTES.toMillis(1));
es.shutdown();
}
catch (InterruptedException e) { System.out.println("Done!"); }
}
public static final class Storage
{
/* AtomicInteger is used so that it can be mutable and final at the same time */
private final AtomicInteger currentCapacity;
private final int maxCapacity;
public Storage(final int maxCapacity) { this(0, maxCapacity); }
public Storage(final int currentCapacity, final int maxCapacity)
{
this.currentCapacity = new AtomicInteger(currentCapacity);
this.maxCapacity = maxCapacity;
}
public int remainingCapacity() { return this.maxCapacity - this.currentCapacity.get(); }
public int getCurrentCapacity() { return this.currentCapacity.get(); }
public void increase(final int q)
{
synchronized (this.currentCapacity)
{
if (this.currentCapacity.get() < this.maxCapacity)
{
this.currentCapacity.addAndGet(q);
}
else
{
throw new FormattedRuntimeException("Max Capacity %d Exceeded!", this.maxCapacity);
}
}
}
public int getMaxCapacity() { return this.maxCapacity; }
public void decrease(final int q)
{
synchronized (this.currentCapacity)
{
if (this.currentCapacity.get() - q >= 0)
{
this.currentCapacity.addAndGet(q * -1);
}
else
{
this.currentCapacity.set(0);
}
}
}
}
}
Notes:
Limit the scope of synchronized blocks to the minimum they need to protect and lock on the object that needs to stay consistent.
The lock object must be marked final or the reference can change and you will be locking on different instances.
The more final the more correct your programs are likely to be the first time.
Jarrod Roberson gave you the "how" half of the answer. Here's the other half--the "why".
Your Supplier object's add() method waits on itself (i.e., on the supplier object), and it notifies itself.
Your Taker object's take() method waits on its self (i.e., on the taker object), and it notifies its self.
The supplier never notifies the taker, and taker never notifies the supplier.
You should do all of your synchronization on the shared object (i.e., on the Storage object.
So I should convert storage into a thread?
No, you don't want Storage to be a thread, you want it to be the lock. Instead of having your Supplier objects and your Taker objects synchronize on themselves, they should all synchronize on the shared Storage object.
E.g., do this:
public void take() {
synchronized(storage) {
while(...) {
try {
storage.wait();
} catch ...
}
...
storage.notifyAll();
}
}
Instead of this:
public synchronized void take() {
while(...) {
try {
wait();
} catch ...
}
...
notifyAll();
}
And do the same for all of your other synchronized methods.
I have the following situation: I'm concurrently processing requests that have a given key. I can process any number of requests at the same time, as long as each key in progress is unique.
I am a total rookie with concurrency in Java. There must be some pattern/utility/existing question for this, but I can't figure out what to search for. Hoping somebody could point me in the right direction, or comment on what I have so far.
This class manages the locks:
class LockMap<K> {
private Map<K, Object> locks = new HashMap<>();
void acquireLock(K key) throws InterruptedException {
Object lockObj;
synchronized (locks) {
lockObj = locks.get(key);
if (lockObj == null) lockObj = new Object();
locks.put(key, lockObj);
}
synchronized (lockObj) {
lockObj.wait();
}
}
void releaseLock(K key) {
Object lockObj;
synchronized (locks) {
lockObj = locks.get(key);
locks.remove(key);
}
if (lockObj != null) {
synchronized (lockObj) {
lockObj.notify();
}
}
}
}
Then I use the lock manager like this:
// lockMap is instance of LockMap shared across all threads
void doSomething(K key) {
lockMap.acquireLock(key);
try {
// something
} finally {
lockMap.releaseLock(key);
}
}
Is this the right way to do it?
How about this:
create a ConcurrentHashMap<K,Semaphore>
ConcurrentMap<K, Semaphore> myMap = new ConcurrentHashMap<>();
in your doSomething() method, use the putIfAbsent() method to of your map to add a semaphore with one permit to the map, only if the key does not exist in the map.
subsequently do a get() on the key to fetch the semaphore for that key, and then do your stuff. Release the semaphore when done.
void doSomething(K key) {
myMap.putIfAbsent(key, new Semaphore(1));
Semaphore s = myMap.get(myKey);
s.aquire();
try {
// do stuff
} finally {
s.release();
}
}
The only real problem with this scheme is if your list of keys will grow indefinitely, I don't have a good race-condition-free strategy for removing the semaphore from the map. (But if you know you will reuse the same keys over and over, or the list will grow slowly, then maybe this is ok.)
Following solution does not locks LockMap and so is extremly parallel. It uses custom-made Locks to track the moment when they can be deleted, and handles concurrent deletion/creation.
class Lock {
boolean busy=true; // locked state, a thread is working
int waitCount=0; // number of waiting threads
/** returns true if lock succeeded */
synchronized boolean tryLock() throws InterruptedException {
if (busy) {
waitCount++;
} else if (waitCount==0){
// such values mean that the lock is deleted
return false;
} else {
busy=true;
return true;
}
for (;;) {
wait();
if (!busy) {
waitCount--;
busy=true;
return true;
}
}
}
}
class LockMap<K> {
private ConcurrentHashMap<K, Lock> locks = new ConcurrentHashMap<>();
void acquireLock(K key) throws InterruptedException {
for (;;) {
Lock lockObj = locks.get(key);
if (lockObj==null) {
Lock myLockObj = new Lock();
lockObj=locks.putIfAbsent(key, myLockObj);
if (lockObj==null) {
// successfully inserted, and so locked
return;
}
}
// lockObj existed, lock it or wait in queue
if (lockObj.tryLock()) {
return;
}
}
}
void releaseLock(K key) {
Lock lockObj = locks.get(key);
synchronized (lockObj) {
lockObj.busy=false;
if (lockObj.waitCount==0) {
locks.remove(key);
} else {
lockObj.notify();
}
}
}
}
I am working on a project in which I am making connections to database. And I need to see how many times an exception is happening if there are any. I am working with Multithreaded code, meaning multiple threads will be making connection to database and inserting into database. So it might be possible that at some point connection get lost so we need to see how many times those exception has occurred.
So I wrote a below code and in the catch block, I am catching exception and making a counter to increased every time if there is any exeption and putting it in ConcurrentHashMap.
class Task implements Runnable {
public static final AtomicInteger counter_sql_exception = new AtomicInteger(0);
public static final AtomicInteger counter_exception = new AtomicInteger(0);
public static ConcurrentHashMap<String, Integer> exceptionMap = new ConcurrentHashMap<String, Integer>();
#Override
public void run() {
try {
//Make a db connection and then executing the SQL-
} catch (SQLException e) {
synchronized(this) {
exceptionMap.put(e.getCause().toString(), counter_sql_exception.incrementAndGet());
}
LOG.Error("Log Exception")
} catch (Exception e) {
synchronized(this) {
exceptionMap.put(e.getCause().toString(), counter_exception.incrementAndGet());
}
LOG.Error("Log Exception")
}
}
}
My Question is- Today I had a code review and one of my senior team members said, you won't be needing synchronized(this) on the exceptionMap in the catch block. I said yes we will be needing because incrementing the counter is atomic. Putting a new value in the map is atomic. But doing both without synchronization is not atomic . And he said ConurrentHashMap will be doing this for you.
So does I will be needing synchronized(this) block on that exceptionMap or not.? If not then why? And if Yes then what reason should I quote to him.
if you are tying to count the number of times each exception occured, then you need something like this:
private static final ConcurrentMap<String, AtomicInteger> exceptionMap = new ConcurrentHashMap<String, AtomicInteger>();
private static void addException(String cause) {
AtomicInteger count = exceptionMap.get(cause);
if(count == null) {
count = new AtomicInteger();
AtomicInteger curCount = exception.putIfAbsent(cause, count);
if(curCount != null) {
count = curCount;
}
}
count.incrementAndGet();
}
note that having a static map of exceptions is a resource leak unless you periodically clean it out.
As #dnault mentioned, you could also use guava's AtomicLongMap.
UPDATE: some comments on your original:
you are correct, that you do need another wrapping synchronized block to ensure that the latest value actually makes it into the map. however, as #Perception already pointed out in comments, you are synchronizing on the wrong object instance (since you are updating static maps, you need a static instance, such as Task.class)
however, you are using a static counter, but a String key which could be different for different exceptions, thus you aren't actually counting each exception cause, but instead sticking random numbers in as various map values
lastly, as i've shown in my example, you can solve the aforementioned issues and discard the synchronized blocks completely by making appropriate use of the ConcurrentMap.
And this way should also work.
private static final ConcurrentMap<String, Integer> exceptionMap = new ConcurrentHashMap<String, Integer>();
private static void addException(String cause) {
Integer oldVal, newVal;
do {
oldVal = exceptionMap .get(cause);
newVal = (oldVal == null) ? 1 : (oldVal + 1);
} while (!queryCounts.replace(q, oldVal, newVal));
}
ConcurrentHashMap doesn't allow null values, so replace will throw exception if called with oldValue == null. I used this code to increase counter by delta with returning oldValue.
private final ConcurrentMap<Integer,Integer> counters = new ConcurrentHashMap<Integer,Integer>();
private Integer counterAddDeltaAndGet(Integer key, Integer delta) {
Integer oldValue = counters.putIfAbsent(key, delta);
if(oldValue == null) return null;
while(!counters.replace(key, oldValue, oldValue + delta)) {
oldValue = counters.get(key);
}
return oldValue;
}
You don't have to use synchronized block and AtomicInteger. You can do it just with ConcurrentHashMap.compute method which is a thread-safe atomic operation. So your code will look something like this
public class Task implements Runnable {
public static final Map<String, Integer> EXCEPTION_MAP = new ConcurrentHashMap<String, Integer>();
#Override
public void run() {
try {
// Make a db connection and then executing the SQL-
} catch (Exception e) {
EXCEPTION_MAP.compute(e.getCause().toString(), (key, value) -> {
if (value == null) {
return 1;
}
return ++value;
});
}
}
}
MySQL has a handy function:
SELECT GET_LOCK("SomeName")
This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.
I have many situations like:
someMethod() {
// do stuff to user A for their data for feature X
}
It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.
With the MySql lock I could do something like:
someMethod() {
executeQuery("SELECT GET_LOCK('userA-featureX')")
// only locked for user A for their data for feature X
executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}
Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.
I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?
Edit:
To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:
LockManager.acquireLock(String name) {
Lock lock;
synchronized (map) {
lock = map.get(name);
// doesn't exist yet - create and store
if(lock == null) {
lock = new Lock();
map.put(name, lock);
}
}
lock.lock();
}
LockManager.releaseLock(String name) {
// unlock
// if this was the last hold on the lock, remove it from the cache
}
All those answers I see are way too complicated. Why not simply use:
public void executeInNamedLock(String lockName, Runnable runnable) {
synchronized(lockName.intern()) {
runnable.run();
}
}
The key point is the method intern: it ensures that the String returned is a global unique object, and so it can be used as a vm-instance-wide mutex. All interned Strings are held in a global pool, so that's your static cache you were talking about in your original question. Don't worry about memleaks; those strings will be gc'ed if no other thread references it. Note however, that up to and including Java6 this pool is kept in PermGen space instead of the heap, so you might have to increase it.
There's a problem though if some other code in your vm locks on the same string for completely different reasons, but a) this is very unlikely, and b) you can get around it by introducing namespaces, e.g. executeInNamedLock(this.getClass().getName() + "_" + myLockName);
Can you have a Map<String, java.util.concurrent.Lock>? Each time you require a lock, you basically call map.get(lockName).lock().
Here's an example using Google Guava:
Map<String, Lock> lockMap = new MapMaker().makeComputingMap(new Function<String, Lock>() {
#Override public Lock apply(String input) {
return new ReentrantLock();
}
});
Then lockMap.get("anyOldString") will cause a new lock to be created if required and returned to you. You can then call lock() on that lock. makeComputingMap returns a Map that is thread-safe, so you can just share that with all your threads.
// pool of names that are being locked
HashSet<String> pool = new HashSet<String>();
lock(name)
synchronized(pool)
while(pool.contains(name)) // already being locked
pool.wait(); // wait for release
pool.add(name); // I lock it
unlock(name)
synchronized(pool)
pool.remove(name);
pool.notifyAll();
maybe this is useful for you: jkeylockmanager
Edit:
My initial response was probably a bit short. I am the author and was faced with this problem several times and could not find an existing solution. That's why I made this small library on Google Code.
Maybe a little later but you can use Google Guava Striped
Conceptually, lock striping is the technique of dividing a lock into many stripes, increasing the granularity of a single lock and allowing independent operations to lock different stripes and proceed concurrently, instead of creating contention for a single lock.
//init
stripes=Striped.lazyWeakLock(size);
//or
stripes=Striped.lock(size);
//...
Lock lock=stripes.get(object);
For locking on something like a user name, in-memory Locks in a map might be a bit leaky. As an alternative, you could look at using WeakReferences with WeakHashMap to create mutex objects that can be garbage collected when nothing refers to them. This avoids you having to do any manual reference counting to free up memory.
You can find an implementation here. Note that if you're doing frequent lookups on the map you may run into contention issues acquiring the mutex.
A generic solution using java.util.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();
}
}
}
Based on the answer of McDowell and his class IdMutexProvider, I have written the generic class LockMap that uses WeakHashMap to store lock objects. LockMap.get() can be used to retrieve a lock object for a key, which can then be used with the Java synchronized (...) statement to apply a lock. Unused lock objects are automatically freed during garbage collection.
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
// A map that creates and stores lock objects for arbitrary keys values.
// Lock objects which are no longer referenced are automatically released during garbage collection.
// Author: Christian d'Heureuse, www.source-code.biz
// Based on IdMutexProvider by McDowell, http://illegalargumentexception.blogspot.ch/2008/04/java-synchronizing-on-transient-id.html
// See also https://stackoverflow.com/questions/5639870/simple-java-name-based-locks
public class LockMap<KEY> {
private WeakHashMap<KeyWrapper<KEY>,WeakReference<KeyWrapper<KEY>>> map;
public LockMap() {
map = new WeakHashMap<KeyWrapper<KEY>,WeakReference<KeyWrapper<KEY>>>(); }
// Returns a lock object for the specified key.
public synchronized Object get (KEY key) {
if (key == null) {
throw new NullPointerException(); }
KeyWrapper<KEY> newKeyWrapper = new KeyWrapper<KEY>(key);
WeakReference<KeyWrapper<KEY>> ref = map.get(newKeyWrapper);
KeyWrapper<KEY> oldKeyWrapper = (ref == null) ? null : ref.get();
if (oldKeyWrapper != null) {
return oldKeyWrapper; }
map.put(newKeyWrapper, new WeakReference<KeyWrapper<KEY>>(newKeyWrapper));
return newKeyWrapper; }
// Returns the number of used entries in the map.
public synchronized int size() {
return map.size(); }
// KeyWrapper wraps a key value and is used in three ways:
// - as the key for the internal WeakHashMap
// - as the value for the internal WeakHashMap, additionally wrapped in a WeakReference
// - as the lock object associated to the key
private static class KeyWrapper<KEY> {
private KEY key;
private int hashCode;
public KeyWrapper (KEY key) {
this.key = key;
hashCode = key.hashCode(); }
public boolean equals (Object obj) {
if (obj == this) {
return true; }
if (obj instanceof KeyWrapper) {
return ((KeyWrapper)obj).key.equals(key); }
return false; }
public int hashCode() {
return hashCode; }}
} // end class LockMap
Example of how to use the LockMap class:
private static LockMap<String> lockMap = new LockMap<String>();
synchronized (lockMap.get(name)) {
...
}
A simple test program for the LockMap class:
public static Object lock1;
public static Object lock2;
public static void main (String[] args) throws Exception {
System.out.println("TestLockMap Started");
LockMap<Integer> map = new LockMap<Integer>();
lock1 = map.get(1);
lock2 = map.get(2);
if (lock2 == lock1) {
throw new Error(); }
Object lock1b = map.get(1);
if (lock1b != lock1) {
throw new Error(); }
if (map.size() != 2) {
throw new Error(); }
for (int i=0; i<10000000; i++) {
map.get(i); }
System.out.println("Size before gc: " + map.size()); // result varies, e.g. 4425760
System.gc();
Thread.sleep(1000);
if (map.size() != 2) {
System.out.println("Size after gc should be 2 but is " + map.size()); }
System.out.println("TestLockMap completed"); }
If anyone knows a better way to automatically test the LockMap class, please write a comment.
I'd like to notice that ConcurrentHashMap has built-in locking facility that is enough for simple exclusive multithread lock. No additional Lock objects needed.
Here is an example of such lock map used to enforce at most one active jms processing for single client.
private static final ConcurrentMap<String, Object> lockMap = new ConcurrentHashMap<String, Object>();
private static final Object DUMMY = new Object();
private boolean tryLock(String key) {
if (lockMap.putIfAbsent(key, DUMMY) != null) {
return false;
}
try {
if (/* attempt cluster-wide db lock via select for update nowait */) {
return true;
} else {
unlock(key);
log.debug("DB is already locked");
return false;
}
} catch (Throwable e) {
unlock(key);
log.debug("DB lock failed", e);
return false;
}
}
private void unlock(String key) {
lockMap.remove(key);
}
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message message) {
String key = getClientKey(message);
if (tryLock(key)) {
try {
// handle jms
} finally {
unlock(key);
}
} else {
// key is locked, forcing redelivery
messageDrivenContext.setRollbackOnly();
}
}
2 years later but I was looking for a simple named locker solution and came across this, was usefull but I needed a simpler answer, so below what I came up with.
Simple lock under some name and release again under that same name.
private void doTask(){
locker.acquireLock(name);
try{
//do stuff locked under the name
}finally{
locker.releaseLock(name);
}
}
Here is the code:
public class NamedLocker {
private ConcurrentMap<String, Semaphore> synchSemaphores = new ConcurrentHashMap<String, Semaphore>();
private int permits = 1;
public NamedLocker(){
this(1);
}
public NamedLocker(int permits){
this.permits = permits;
}
public void acquireLock(String... key){
Semaphore tempS = new Semaphore(permits, true);
Semaphore s = synchSemaphores.putIfAbsent(Arrays.toString(key), tempS);
if(s == null){
s = tempS;
}
s.acquireUninterruptibly();
}
public void releaseLock(String... key){
Semaphore s = synchSemaphores.get(Arrays.toString(key));
if(s != null){
s.release();
}
}
}
Many implementations but non similar to mine.
Called my Dynamic lock implementation as ProcessDynamicKeyLock because it's a single process lock, for any object as key (equals+hashcode for uniqueness).
TODO: Add a way to provide the actual lock, for example, ReentrantReadWriteLock instead of ReentrantLock.
Implementation:
public class ProcessDynamicKeyLock<T> implements Lock
{
private final static ConcurrentHashMap<Object, LockAndCounter> locksMap = new ConcurrentHashMap<>();
private final T key;
public ProcessDynamicKeyLock(T lockKey)
{
this.key = lockKey;
}
private static class LockAndCounter
{
private final Lock lock = new ReentrantLock();
private final AtomicInteger counter = new AtomicInteger(0);
}
private LockAndCounter getLock()
{
return locksMap.compute(key, (key, lockAndCounterInner) ->
{
if (lockAndCounterInner == null) {
lockAndCounterInner = new LockAndCounter();
}
lockAndCounterInner.counter.incrementAndGet();
return lockAndCounterInner;
});
}
private void cleanupLock(LockAndCounter lockAndCounterOuter)
{
if (lockAndCounterOuter.counter.decrementAndGet() == 0)
{
locksMap.compute(key, (key, lockAndCounterInner) ->
{
if (lockAndCounterInner == null || lockAndCounterInner.counter.get() == 0) {
return null;
}
return lockAndCounterInner;
});
}
}
#Override
public void lock()
{
LockAndCounter lockAndCounter = getLock();
lockAndCounter.lock.lock();
}
#Override
public void unlock()
{
LockAndCounter lockAndCounter = locksMap.get(key);
lockAndCounter.lock.unlock();
cleanupLock(lockAndCounter);
}
#Override
public void lockInterruptibly() throws InterruptedException
{
LockAndCounter lockAndCounter = getLock();
try
{
lockAndCounter.lock.lockInterruptibly();
}
catch (InterruptedException e)
{
cleanupLock(lockAndCounter);
throw e;
}
}
#Override
public boolean tryLock()
{
LockAndCounter lockAndCounter = getLock();
boolean acquired = lockAndCounter.lock.tryLock();
if (!acquired)
{
cleanupLock(lockAndCounter);
}
return acquired;
}
#Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException
{
LockAndCounter lockAndCounter = getLock();
boolean acquired;
try
{
acquired = lockAndCounter.lock.tryLock(time, unit);
}
catch (InterruptedException e)
{
cleanupLock(lockAndCounter);
throw e;
}
if (!acquired)
{
cleanupLock(lockAndCounter);
}
return acquired;
}
#Override
public Condition newCondition()
{
LockAndCounter lockAndCounter = locksMap.get(key);
return lockAndCounter.lock.newCondition();
}
}
Simple test:
public class ProcessDynamicKeyLockTest
{
#Test
public void testDifferentKeysDontLock() throws InterruptedException
{
ProcessDynamicKeyLock<Object> lock = new ProcessDynamicKeyLock<>(new Object());
lock.lock();
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
try
{
new Thread(() ->
{
ProcessDynamicKeyLock<Object> anotherLock = new ProcessDynamicKeyLock<>(new Object());
anotherLock.lock();
try
{
anotherThreadWasExecuted.set(true);
}
finally
{
anotherLock.unlock();
}
}).start();
Thread.sleep(100);
}
finally
{
Assert.assertTrue(anotherThreadWasExecuted.get());
lock.unlock();
}
}
#Test
public void testSameKeysLock() throws InterruptedException
{
Object key = new Object();
ProcessDynamicKeyLock<Object> lock = new ProcessDynamicKeyLock<>(key);
lock.lock();
AtomicBoolean anotherThreadWasExecuted = new AtomicBoolean(false);
try
{
new Thread(() ->
{
ProcessDynamicKeyLock<Object> anotherLock = new ProcessDynamicKeyLock<>(key);
anotherLock.lock();
try
{
anotherThreadWasExecuted.set(true);
}
finally
{
anotherLock.unlock();
}
}).start();
Thread.sleep(100);
}
finally
{
Assert.assertFalse(anotherThreadWasExecuted.get());
lock.unlock();
}
}
}
Another possible solution which I have implemented and tested when encountered the same requirements as the original poster.
In this solution:
No external libraries
Not leaving unused objects in memory
Minimal usage of synchronized and minimal "cross-names" locking
No downsides of using intern
Helper class code:
public class IdBasedLockHelper<T> {
private final static AtomicIntegerWithEquals zero = new AtomicIntegerWithEquals(0);
private final ConcurrentMap<T, AtomicIntegerWithEquals> identifierToLockCounter = new ConcurrentHashMap<>();
public void executeLocked(T lockId, Runnable runnable) {
AtomicIntegerWithEquals counterAndLock = identifierToLockCounter.compute(lockId, (key, existing) -> {
if (existing == null) {
return new AtomicIntegerWithEquals(1);
}
existing.atomicValue.incrementAndGet();
return existing;
});
synchronized (counterAndLock) {
try {
runnable.run();
} finally {
counterAndLock.atomicValue.decrementAndGet();
identifierToLockCounter.remove(lockId, zero);
}
}
}
// AtomicInteger does not implement equals() properly so there is a need for such wrapper
private static class AtomicIntegerWithEquals {
private final AtomicInteger atomicValue;
AtomicIntegerWithEquals(int value) {
this.atomicValue = new AtomicInteger(value);
}
// Used internally by remove()
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IdBasedLockHelper.AtomicIntegerWithEquals)) return false;
return atomicValue.get() == ((AtomicIntegerWithEquals) o).atomicValue.get();
}
// Not really used, but when implementing custom equals() it is a good practice to implement also hashCode()
#Override
public int hashCode() {
return atomicValue.get();
}
}
}
Usage:
IdBasedLockHelper<String> idBasedLockHelper = new IdBasedLockHelper<>();
idBasedLockHelper.executeLocked("Some Name", () -> {
// Your code to execute synchronized per name
});
ConcurrentHashMap is used to store synchronization object for each lock id.
ConcurrentHashMap already provides compute and remove (if value equals) as atomic operations. The AtomicInteger inside the stored value counts the number of holds of the synchronization object and this allows removing it from the map only if it is not in use (number of holds equals 0).
Maybe something like that:
public class ReentrantNamedLock {
private class RefCounterLock {
public int counter;
public ReentrantLock sem;
public RefCounterLock() {
counter = 0;
sem = new ReentrantLock();
}
}
private final ReentrantLock _lock = new ReentrantLock();
private final HashMap<String, RefCounterLock> _cache = new HashMap<String, RefCounterLock>();
public void lock(String key) {
_lock.lock();
RefCounterLock cur = null;
try {
if (!_cache.containsKey(key)) {
cur = new RefCounterLock();
_cache.put(key, cur);
} else {
cur = _cache.get(key);
}
cur.counter++;
} finally {
_lock.unlock();
}
cur.sem.lock();
}
public void unlock(String key) {
_lock.lock();
try {
if (_cache.containsKey(key)) {
RefCounterLock cur = _cache.get(key);
cur.counter--;
cur.sem.unlock();
if (cur.counter == 0) { //last reference
_cache.remove(key);
}
cur = null;
}
} finally {
_lock.unlock();
}
}}
I didn't test it though.
After some disappointment that there is no language level support or simple Guava/Commons class for named locks,
This is what I settled down to:
ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
Object getLock(String name) {
Object lock = locks.get(name);
if (lock == null) {
Object newLock = new Object();
lock = locks.putIfAbsent(name, newLock);
if (lock == null) {
lock = newLock;
}
}
return lock;
}
void somethingThatNeedsNamedLocks(String name) {
synchronized(getLock(name)) {
// some operations mutually exclusive per each name
}
}
Here I achieved: little boilerplate code with no library dependency, atomically acquiring the lock object, not polluting the global interned string objects, no low-level notify/wait chaos and no try-catch-finally mess.
Similar to the answer from Lyomi, but uses the more flexible ReentrantLock instead of a synchronized block.
public class NamedLock
{
private static final ConcurrentMap<String, Lock> lockByName = new ConcurrentHashMap<String, Lock>();
public static void lock(String key)
{
Lock lock = new ReentrantLock();
Lock existingLock = lockByName.putIfAbsent(key, lock);
if(existingLock != null)
{
lock = existingLock;
}
lock.lock();
}
public static void unlock(String key)
{
Lock namedLock = lockByName.get(key);
namedLock.unlock();
}
}
Yes this will grow over time - but using the ReentrantLock opens up greater possibilities for removing the lock from the map. Although, removing items from the map doesn't seem all that useful considering removing values from the map will not shrink its size. Some manual map sizing logic would have to be implemented.
Memory consideration
Often times, synchronization needed for a particular key is short-lived. Keeping around released keys can lead to excessive memory waste, making it non-viable.
Here's an implementation does not internally keep around released keys.
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
public class KeyedMutexes<K> {
private final ConcurrentMap<K, CountDownLatch> key2Mutex = new ConcurrentHashMap<>();
public void lock(K key) throws InterruptedException {
final CountDownLatch ourLock = new CountDownLatch(1);
for (;;) {
CountDownLatch theirLock = key2Mutex.putIfAbsent(key, ourLock);
if (theirLock == null) {
return;
}
theirLock.await();
}
}
public void unlock(K key) {
key2Mutex.remove(key).countDown();
}
}
Reentrancy, and other bells and whistles
If one wants re-entrant lock semantics, they can extend the above by wrapping the mutex object in a class that keeps track of the locking thread and locked count.
e.g.:
private static class Lock {
final CountDownLatch mutex = new CountDownLatch(1);
final long threadId = Thread.currentThread().getId();
int lockedCount = 1;
}
If one wants lock() to return an object to make releases easier and safer, that's also a possibility.
Putting it all together, here's what the class could look like:
public class KeyedReentrantLocks<K> {
private final ConcurrentMap<K, KeyedLock> key2Lock = new ConcurrentHashMap<>();
public KeyedLock acquire(K key) throws InterruptedException {
final KeyedLock ourLock = new KeyedLock() {
#Override
public void close() {
if (Thread.currentThread().getId() != threadId) {
throw new IllegalStateException("wrong thread");
}
if (--lockedCount == 0) {
key2Lock.remove(key);
mutex.countDown();
}
}
};
for (;;) {
KeyedLock theirLock = key2Lock.putIfAbsent(key, ourLock);
if (theirLock == null) {
return ourLock;
}
if (theirLock.threadId == Thread.currentThread().getId()) {
theirLock.lockedCount++;
return theirLock;
}
theirLock.mutex.await();
}
}
public static abstract class KeyedLock implements AutoCloseable {
protected final CountDownLatch mutex = new CountDownLatch(1);
protected final long threadId = Thread.currentThread().getId();
protected int lockedCount = 1;
#Override
public abstract void close();
}
}
And here's how one might use it:
try (KeyedLock lock = locks.acquire("SomeName")) {
// do something critical here
}
In response to the suggestion of using new MapMaker().makeComputingMap()...
MapMaker().makeComputingMap() is deprecated for safety reasons. The successor is CacheBuilder. With weak keys/values applied to CacheBuilder, we're soooo close to a solution.
The problem is a note in CacheBuilder.weakKeys():
when this method is used, the resulting cache will use identity (==) comparison to determine equality of keys.
This makes it impossible to select an existing lock by string value. Erg.
(4 years later...)
My answer is similar to user2878608's but I think there are some missing edge cases in that logic. I also thought Semaphore was for locking multiple resources at once (though I suppose using it for counting lockers like that is fine too), so I used a generic POJO lock object instead. I ran one test on it which demonstrated each of the edge cases existed IMO and will be using it on my project at work. Hope it helps someone. :)
class Lock
{
int c; // count threads that require this lock so you don't release and acquire needlessly
}
ConcurrentHashMap<SomeKey, Lock> map = new ConcurrentHashMap<SomeKey, Lock>();
LockManager.acquireLock(String name) {
Lock lock = new Lock(); // creating a new one pre-emptively or checking for null first depends on which scenario is more common in your use case
lock.c = 0;
while( true )
{
Lock prevLock = map.putIfAbsent(name, lock);
if( prevLock != null )
lock = prevLock;
synchronized (lock)
{
Lock newLock = map.get(name);
if( newLock == null )
continue; // handles the edge case where the lock got removed while someone was still waiting on it
if( lock != newLock )
{
lock = newLock; // re-use the latest lock
continue; // handles the edge case where a new lock was acquired and the critical section was entered immediately after releasing the lock but before the current locker entered the sync block
}
// if we already have a lock
if( lock.c > 0 )
{
// increase the count of threads that need an offline director lock
++lock.c;
return true; // success
}
else
{
// safely acquire lock for user
try
{
perNameLockCollection.add(name); // could be a ConcurrentHashMap or other synchronized set, or even an external global cluster lock
// success
lock.c = 1;
return true;
}
catch( Exception e )
{
// failed to acquire
lock.c = 0; // this must be set in case any concurrent threads are waiting
map.remove(name); // NOTE: this must be the last critical thing that happens in the sync block!
}
}
}
}
}
LockManager.releaseLock(String name) {
// unlock
// if this was the last hold on the lock, remove it from the cache
Lock lock = null; // creating a new one pre-emptively or checking for null first depends on which scenario is more common in your use case
while( true )
{
lock = map.get(name);
if( lock == null )
{
// SHOULD never happen
log.Error("found missing lock! perhaps a releaseLock call without corresponding acquireLock call?! name:"+name);
lock = new Lock();
lock.c = 1;
Lock prevLock = map.putIfAbsent(name, lock);
if( prevLock != null )
lock = prevLock;
}
synchronized (lock)
{
Lock newLock = map.get(name);
if( newLock == null )
continue; // handles the edge case where the lock got removed while someone was still waiting on it
if( lock != newLock )
{
lock = newLock; // re-use the latest lock
continue; // handles the edge case where a new lock was acquired and the critical section was entered immediately after releasing the lock but before the current locker entered the sync block
}
// if we are not the last locker
if( lock.c > 1 )
{
// decrease the count of threads that need an offline director lock
--lock.c;
return true; // success
}
else
{
// safely release lock for user
try
{
perNameLockCollection.remove(name); // could be a ConcurrentHashMap or other synchronized set, or even an external global cluster lock
// success
lock.c = 0; // this must be set in case any concurrent threads are waiting
map.remove(name); // NOTE: this must be the last critical thing that happens in the sync block!
return true;
}
catch( Exception e )
{
// failed to release
log.Error("unable to release lock! name:"+name);
lock.c = 1;
return false;
}
}
}
}
}
I've created a tokenProvider based on the IdMutexProvider of McDowell.
The manager uses a WeakHashMap which takes care of cleaning up unused locks.
TokenManager:
/**
* Token provider used to get a {#link Mutex} object which is used to get exclusive access to a given TOKEN.
* Because WeakHashMap is internally used, Mutex administration is automatically cleaned up when
* the Mutex is no longer is use by any thread.
*
* <pre>
* Usage:
* private final TokenMutexProvider<String> myTokenProvider = new TokenMutexProvider<String>();
*
* Mutex mutex = myTokenProvider.getMutex("123456");
* synchronized (mutex) {
* // your code here
* }
* </pre>
*
* Class inspired by McDowell.
* url: http://illegalargumentexception.blogspot.nl/2008/04/java-synchronizing-on-transient-id.html
*
* #param <TOKEN> type of token. It is important that the equals method of that Object return true
* for objects of different instances but with the same 'identity'. (see {#link WeakHashMap}).<br>
* E.g.
* <pre>
* String key1 = "1";
* String key1b = new String("1");
* key1.equals(key1b) == true;
*
* or
* Integer key1 = 1;
* Integer key1b = new Integer(1);
* key1.equals(key1b) == true;
* </pre>
*/
public class TokenMutexProvider<TOKEN> {
private final Map<Mutex, WeakReference<Mutex>> mutexMap = new WeakHashMap<Mutex, WeakReference<Mutex>>();
/**
* Get a {#link Mutex} for the given (non-null) token.
*/
public Mutex getMutex(TOKEN token) {
if (token==null) {
throw new NullPointerException();
}
Mutex key = new MutexImpl(token);
synchronized (mutexMap) {
WeakReference<Mutex> ref = mutexMap.get(key);
if (ref==null) {
mutexMap.put(key, new WeakReference<Mutex>(key));
return key;
}
Mutex mutex = ref.get();
if (mutex==null) {
mutexMap.put(key, new WeakReference<Mutex>(key));
return key;
}
return mutex;
}
}
public int size() {
synchronized (mutexMap) {
return mutexMap.size();
}
}
/**
* Mutex for acquiring exclusive access to a token.
*/
public static interface Mutex {}
private class MutexImpl implements Mutex {
private final TOKEN token;
protected MutexImpl(TOKEN token) {
this.token = token;
}
#Override
public boolean equals(Object other) {
if (other==null) {
return false;
}
if (getClass()==other.getClass()) {
TOKEN otherToken = ((MutexImpl)other).token;
return token.equals(otherToken);
}
return false;
}
#Override
public int hashCode() {
return token.hashCode();
}
}
}
Usage:
private final TokenMutexManager<String> myTokenManager = new TokenMutexManager<String>();
Mutex mutex = myTokenManager.getMutex("UUID_123456");
synchronized(mutex) {
// your code here
}
or rather use Integers?
private final TokenMutexManager<Integer> myTokenManager = new TokenMutexManager<Integer>();
Mutex mutex = myTokenManager.getMutex(123456);
synchronized(mutex) {
// your code here
}
This thread is old, but a possible solution is the framework https://github.com/brandaof/named-lock.
NamedLockFactory lockFactory = new NamedLockFactory();
...
Lock lock = lockFactory.getLock("lock_name");
lock.lock();
try{
//manipulate protected state
}
finally{
lock.unlock();
}
Here is a simple and optimized solution which addresses the removal of used locks also, but with an overhead of synchronization of the Map:
public class NamedLock {
private Map<String, ReentrantLock> lockMap;
public NamedLock() {
lockMap = new HashMap<>();
}
public void lock(String... name) {
ReentrantLock newLock = new ReentrantLock(true);
ReentrantLock lock;
synchronized (lockMap) {
lock = Optional.ofNullable(lockMap.putIfAbsent(Arrays.toString(name), newLock)).orElse(newLock);
}
lock.lock();
}
public void unlock(String... name) {
ReentrantLock lock = lockMap.get(Arrays.toString(name));
synchronized (lockMap) {
if (!lock.hasQueuedThreads()) {
lockMap.remove(name);
}
}
lock.unlock();
}
}
Your idea about a shared static repository of lock objects for each situation is correct.
You don't need the cache itself to be synchronized ... it can be as simple as a hash map.
Threads can simultaneously get a lock object from the map. The actual synchronization logic should be encapsulated within each such object separately (see the java.util.concurrent package for that - http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html)
TreeMap because in HashMap size of inner array can only increase
public class Locker<T> {
private final Object lock = new Object();
private final Map<T, Value> map = new TreeMap<T, Value>();
public Value<T> lock(T id) {
Value r;
synchronized (lock) {
if (!map.containsKey(id)) {
Value value = new Value();
value.id = id;
value.count = 0;
value.lock = new ReentrantLock();
map.put(id, value);
}
r = map.get(id);
r.count++;
}
r.lock.lock();
return r;
}
public void unlock(Value<T> r) {
r.lock.unlock();
synchronized (lock) {
r.count--;
if (r.count == 0)
map.remove(r.id);
}
}
public static class Value<T> {
private Lock lock;
private long count;
private T id;
}
}