[concurrency-interest] Named locks with String values

Gregg Wonderly gregg at cytetech.com
Mon Nov 7 20:52:32 EST 2005


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 quick check with and without the intern() call validated that the uniqueness 
of intern() appeared to provide the locking that I needed.

I haven't seen String.intern() mentioned here as a way to get named locks and so 
I was curious of others comments about this usage and whether there are other 
interesting exploits of using other JVM caches.

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

Gregg Wonderly


More information about the Concurrency-interest mailing list