Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple Java name based locks?
    primarykey
    data
    text
    <p>MySQL has a handy function:</p> <pre><code>SELECT GET_LOCK("SomeName") </code></pre> <p>This can be used to create simple, but very specific, name based locks for an application. However, it requires a database connection.</p> <p>I have many situations like:</p> <pre><code>someMethod() { // do stuff to user A for their data for feature X } </code></pre> <p>It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.</p> <p>With the MySql lock I could do something like:</p> <pre><code>someMethod() { executeQuery("SELECT GET_LOCK('userA-featureX')") // only locked for user A for their data for feature X executeQuery("SELECT RELEASE_LOCK('userA-featureX')") } </code></pre> <p>Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.</p> <p>I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?</p> <p><strong>Edit:</strong></p> <p>To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo code for what I am thinking is:</p> <pre><code>LockManager.acquireLock(String name) { Lock lock; synchronized (map) { lock = map.get(name); // doesn't exist yet - create and store if(lock == null) { lock = new Lock(); map.put(name, lock); } } lock.lock(); } LockManager.releaseLock(String name) { // unlock // if this was the last hold on the lock, remove it from the cache } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload