Mysql locking – How to acquire a lock in the DB for each userId

concurrencyinnodblockingMySQL

Hi I have a J2EE Server(clustered) that executes requests from multiple users.

I would like that each request of a given user will be handled like so:

{
  acquireLockForUser(userId); // i.e. insert a lock row for a dedicated table
  doSomeStuffInDbForUser(user);
  releaseLock(userId);  // i.e. delete a lock row from the dedicated table
}

This will make sure that each user request will be handled by a single thread of my servers.

Whats the way to achieve that? (Is it possible to insert into a table 'userLock' by id and lock it? how to insert\fetch from this "lock" table?)

Best Answer

GET_LOCK('rick');
...
RELEASE_LOCK('rick');

During ..., any other thread trying to do GET_LOCK('rick') would be blocked.

Will that work for your application?

Be aware of the caveats: A disconnect (eg, network glitch) will release the lock. Multiple locks need some care. Etc.