[concurrency-interest] Named locks with String values

Dawid Kurzyniec dawidk at mathcs.emory.edu
Thu Nov 10 02:47:48 EST 2005

Gregg Wonderly wrote:

> I recently was working on some code where a method had to string 
> values comming into it, and these values indicate a SQL database 
> rowset that I want to lock access to.  I was trying to decide how I 
> wanted to the locking and then it dawned on me that I could do the 
> following.
>     public void getEntries( String use, String key, ... ) {
>         synchronized( (use+"/"+key).intern() ) {
>             ...
>         }
>     }
I was hoping that some EG member would comment, but in the absence of that:

This looks reasonably legit to me, although feels a bit risky. One 
possible caveat is that it is "external" synchronization, and some other 
library used by your program might independently have the same idea. 
Then you can possibly get into deadlocks: even if you enforce consistent 
lock ordering, or if your code never obtains more than a single lock, 
when combined with unknown library code, it may result in trying to 
acquire two locks from two threads in a different order.

> I understand that this can cause some extended memory growth if use 
> and key are not reasonably bounded in possible values.

I think that smart enough JVM would make the intern cache weak, but you 
never know.

All in all, I would probably rather implement my own weak named lock 
pool, just to be sure that nothing bad like that can happen.


More information about the Concurrency-interest mailing list