There may be a simple way to let your database take care of this for you. I am admittedly weak in knowledge when it comes to databases. In lieu of that, here is an approach that involves creating an individual lock for each key name. There is a single repository that manages the creation/destruction of the individual locks that requires a one-for-the-entire-application lock, but it only holds that lock while the individual key-name lock is being found, created, or destroyed. The lock that is held for the actual database operation is exclusive to the key name being used in that operation.
The KeyLock class is used to prevent simultaneous database operations on a single key name.
package KeyLocks;
import java.util.concurrent.locks.Lock;
public class KeyLock
{
private final KeyLockManager keyLockManager;
private final String keyName;
private final Lock lock;
KeyLock(KeyLockManager keyLockManager, String keyName, Lock lock)
{
this.keyLockManager = keyLockManager;
this.keyName = keyName;
this.lock = lock;
}
@Override
protected void finalize()
{
release();
}
public void release()
{
keyLockManager.releaseLock(keyName);
}
public void lock()
{
lock.lock();
}
public void unlock()
{
lock.unlock();
}
}
The KeyLockManager class is the repository that is responsible for the lifetimes of the key locks.
package KeyLocks;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class KeyLockManager
{
private class LockEntry
{
int acquisitionCount = 0;
final Lock lock = new ReentrantLock();
}
private final Map<String, LockEntry> locks = new HashMap<String, LockEntry>();
private final Object mutex = new Object();
public KeyLock getLock(String keyName)
{
synchronized (mutex)
{
LockEntry lockEntry = locks.get(keyName);
if (lockEntry == null)
{
lockEntry = new LockEntry();
locks.put(keyName, lockEntry);
}
lockEntry.acquisitionCount++;
return new KeyLock(this, keyName, lockEntry.lock);
}
}
void releaseLock(String keyName)
{
synchronized (mutex)
{
LockEntry lockEntry = locks.get(keyName);
lockEntry.acquisitionCount--;
if (lockEntry.acquisitionCount == 0)
{
locks.remove(keyName);
}
}
}
}
Here is a sample of how you would use a key lock.
package test;
import KeyLocks.KeyLock;
import KeyLocks.KeyLockManager;
public class Main
{
private static final String KEY_NAME = "TEST_KEY";
public static void main(String[] args)
{
final KeyLockManager keyLockManager = new KeyLockManager();
KeyLock keyLock = null;
try
{
keyLock = keyLockManager.getLock(KEY_NAME);
keyLock.lock();
try
{
// Do database operation on the data with the specified key name
}
finally
{
keyLock.unlock();
}
}
finally
{
if (keyLock != null)
{
keyLock.release();
}
}
}
}