Synchronizing java threads on a string value

We had a situation where we wanted to synchronize all threads to get a new value from database. This was purely a database design issue but a month effort to fix whole thing so we decided to write a code which can wait for database operation to get completed. This required a synchronization mechanism on value instead of an object. Below is the code.

I wrote a mechanism to clean up synchSemaphores object but it is advisable to use LRUMap or similar API which does it automatically.

One can also remove lockAcquiredCounter object, this was only used for cleaning up process with my custom code.

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;

public final class SemaphoreLocker {
	
	private ConcurrentMap<String, Semaphore> synchSemaphores = new ConcurrentHashMap<String, Semaphore>();
	private long timeToClear = 5;
    private static SemaphoreLocker locker = new SemaphoreLocker();
    
    public static SemaphoreLocker getInstance(){
    	return locker;
    }
    
    /**
     * Constructor will initialize the thread which will do the cleanup when nobody is making any request
     */
    private SemaphoreLocker(){
        // Write a code which can clean	synchSemaphores objects periodically. 
    }
    
    /*
     * Indicator if any thread under lock mode
     */
    volatile int lockAcquiredCounter = 0;
    
    public void acquireLock(String key){
    	synchronized (locker) {
    		lockAcquiredCounter++;
		}
        Semaphore tempS = new Semaphore(1, true);
        Semaphore s = synchSemaphores.putIfAbsent(key, tempS);
        if(s == null){
            s = tempS;
        }
        s.acquireUninterruptibly();
    }

    public void releaseLock(String key){
        Semaphore s = synchSemaphores.get(key);
        if(s != null){
            s.release();
        }
        synchronized (locker) {
    		lockAcquiredCounter--;
		}
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *