Flow Block Based on Function Input

I got into a situation where I have to synchronize a function based on input. eg. There is a function. func (int a) --- this function can be called by many threads. I want to block threads if they try to call this function with the same integer. Otherwise, let them continue without continuing. I wrote a function

HashTable<Integer> check=new Hashtable<Integer>(); func(int a){ Integer lock=check.get(a); if(lock==null){ check.put(a); }else{ check.put(a); } synchronized(lock){ //do something.... 

}}

Please let me know if this is correct. Also, if there is another solution besides this. I try to understand. If I find an answer, I will send it.

+4
source share
1 answer

1) the receipt of the lock must also be in the synchronized block

2) there is a memory leak - you do not remove unused locks

I would do it this way

 Map<Integer, Lock> map = new HashMap<>(); static class Lock { int count = 1; } void func(int i) { Object lock = getLock(i); try { synchronized (lock) { // } } finally { releaseLock(i); } } private synchronized Object getLock(int i) { Lock lock = map.get(i); if (lock != null) { lock.count++; } else { lock = new Lock(); map.put(i, lock); } return lock; } private synchronized void releaseLock(int i) { Lock lock = map.get(i); if (--lock.count == 0) { map.remove(i); } } 
+1
source

Source: https://habr.com/ru/post/1480375/


All Articles