views:

47

answers:

3

I need to prevent simultaneous edits to a database field. Users are executing a push operation on a structured data field, so I want to sequence the operations, not simply ignore one edit and take the second.

Essentially I want to do

synchronized(key name)
{
  push value onto the database field
}

and set up the synchronized item so that only one operation on "key name" will occur at a time. (note: I'm simplifying, it's not always a simple push).

A crude way to do this would be a global synchronization, but that bottlenecks the entire app. All I need to do is sequence two simultaneous writes with the same key, which is rare but annoying occurrence.

This is a web-based java app, written with Spring (and using JPA/MySQL). The operation is triggered by a user web service call. (the root cause is when a user sends two simultaneous http requests with the same key).

I've glanced through the Doug Lea/Josh Bloch/et al Concurrency in Action, but don't see an obvious solution. Still, this seems simple enough I feel there must be an elegant way to do this.

A: 

I think you may be looking for transactions http://www.jpox.org/docs/1_2/jpa/transaction_types.html and http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html

Finbarr
not applicable here. I need both edits to go through in sequence. Each one takes the existing data, inserts a new field into a structured object, then stores it. If they are independent transactions unaware of each other's changes this doesn't work.
Will Glass
+1  A: 

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();
            }
        }
    }
}
Matthew T. Staebler
nice. easy to implement and more importantly, easy to call in the code. Doesn't lock more than is needed, either. Exactly what I was looking for.
Will Glass
@Will. Please be aware that this solution does not guarantee any ordering. If there are two requests involved in the same key, then there is no guarantee about which request will be handled first. It is not clear from what you have presented whether you do or do not have an ordering requirement. I just wanted you to be aware that this solution does not preserve order.
Matthew T. Staebler
that makes sense, since these are essentially simultaneous requests.
Will Glass
I implemented this, and it almost works, but there is an error. The finalize method on KeyLock causes the lock to be released twice. In a multithreaded situation, this causes an NPE in release when a legitimate thread releases a lock.The unfortunate part is that you are assuming the caller is good enough to properly release the lock. I assume if I felt strongly I could use an interrupting lock and clean it up periodically, but this solution is pretty good. (after removing the finalizer).
Will Glass
The solution for that is to add some type of flag that a KeyLock object can maintain indicating whether the lock has been released. The release method should then check to see whether the lock has already been released prior to actually performing the release. After performing the release, the flag should then be modified to indicate that the release has been done.
Matthew T. Staebler
+1  A: 

Even if you lock the key, you cannot ensure it is the same (not only an equal) key next time. What you need is something like select for update done by the database. If this is not possible, you need to lock the key yourself programatic using a synchronized set of locked keys as a member of your repository/dao.

Arne Burmeister
yes, exactly. I'm basically asking for help with the programmatic solution.
Will Glass
actually, Select for Update looks relevant to the general case. I prefer the programmatic solution rather than specialized MySQL commands though as it lets me use my existing Spring/JPA abstraction.
Will Glass