[concurrency-interest] problem with ReentrantReadWriteLock toimplement atomic function

Kolbjørn Aambø kaa at pax.priv.no
Tue Jun 20 07:34:05 EDT 2006


Thanks! You have pointed out what solved the problem:

	public V put(K key, V value)
		throws NullPointerException{
	// Tested to be lock robust for upt to 300K Objects 060608
		boolean hasValue = V_K.containsKey(value);
		boolean hasKey = K_V.containsKey(key);
		V value2 = null;
		
		r.lock();
		try {
			hasValue = V_K.containsKey(value);
			hasKey = K_V.containsKey(key);

			if (!hasValue){// No preexisting occurrence of value
				r.unlock();// Upgrading the lock to write lock
				w.lock();
				if (hasKey) V_K.remove(K_V.get(key));
				
				V_K.put(value, key);
				value2 = K_V.put(key, value);
				
				r.lock();	// Downgrading the lock to read lock
				w.unlock(); //
			}
		} finally {
			r.unlock();
		}		
		return value2;
	}// put(..)


To reiterate on Davids point on OutOfMemoryError - Since put(..)  
throws  NullPointerException which is an extension of  
RunTimeException I would like to compleat both puts or none of them,  
for instance... So I would have to try doing one of them and if  
necessary reversing with the risk of that not working.... Any comments?

Thank you for all help!

Kolbjørn Aambø, Oslo





On Jun 20, 2006, at 11:50 AM, Joe Bowbeer wrote:

> On 6/20/06, Joe Bowbeer <joe.bowbeer at gmail.com> wrote:
>> On 6/20/06, Kolbjørn Aambø <kaa at pax.priv.no> wrote:
>> >
>> > I suspect that the maximum number of locks (65536 recursive  
>> write locks
>> > and 65536 read locks) happen to be the problem here.
>> >
>>
>> That seems likely.  The exception was probably thrown from r.unlock()
>> inside a finally block -- after w.lock() or r.lock() threw an Error.
>>
>> (If you were to retain this code I'd suggest adding a "locked" flag
>> and/or more try-finally nesting in order to disambiguate this
>> condition. This would also protect against "put" failures, as David
>> points out.)
>>
>
> More:
>
> Was the write lock getting downgraded correctly?
>
>  if (!hasValue) {
>      r.unlock();
>      w.lock();
>      if (hasKey) V_K.remove(K_V.get(key));
>      V_K.put(value, key);
>      value2 = K_V.put(key, value);
>      r.lock(); // Downgrading the lock to read lock
>  }
>
> Isn't the above missing a final write unlock?
>
>    w.unlock(); // unlock write, still hold read
>
> The following is from ReentrantReadWriteLock javadoc:
>
>    // downgrade lock
>    rwl.readLock().lock(); // reacquire read without giving up write  
> lock
>    rwl.writeLock().unlock(); // unlock write, still hold read
>
> --Joe

-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20060620/dc8e6b7f/attachment-0001.html 


More information about the Concurrency-interest mailing list