Author: manik.surtani(a)jboss.com
Date: 2009-03-19 05:59:50 -0400 (Thu, 19 Mar 2009)
New Revision: 7920
Modified:
core/trunk/src/main/java/org/jboss/cache/util/concurrent/locks/PerElementLockContainer.java
Log:
JBCACHE-1494 - better impl
Modified:
core/trunk/src/main/java/org/jboss/cache/util/concurrent/locks/PerElementLockContainer.java
===================================================================
---
core/trunk/src/main/java/org/jboss/cache/util/concurrent/locks/PerElementLockContainer.java 2009-03-19
08:35:15 UTC (rev 7919)
+++
core/trunk/src/main/java/org/jboss/cache/util/concurrent/locks/PerElementLockContainer.java 2009-03-19
09:59:50 UTC (rev 7920)
@@ -17,9 +17,10 @@
protected abstract Lock newLock();
- public Lock getLock(E object)
+ public final Lock getLock(E object)
{
- Lock l = newLock();
+ Lock l = locks.get(object);
+ if (l == null) l = newLock();
Lock tmp = locks.putIfAbsent(object, l);
if (tmp != null) l = tmp;
return l;
@@ -53,30 +54,51 @@
public void acquireLock(E object)
{
- Lock l = getLock(object);
- l.lock();
- // now check that the lock is still valid...
- if (l != locks.get(object))
+ while (true)
{
- // we acquired the wrong lock!
- l.unlock();
- acquireLock(object);
+ Lock lock = getLock(object);
+ lock.lock();
+ // now check that the lock is still valid...
+ Lock currentLock = locks.putIfAbsent(object, lock);
+ if (currentLock != null && lock != currentLock)
+ {
+ // we acquired the wrong lock!
+ lock.unlock();
+ }
+ else
+ {
+ // we got the right lock!
+ break;
+ }
}
}
public boolean acquireLock(E object, long timeout, TimeUnit unit) throws
InterruptedException
{
- Lock l = getLock(object);
- boolean result = l.tryLock(timeout, unit);
-
- // now check that the lock is still valid...
- if (result && l != locks.get(object))
+ while (true)
{
- // we acquired the wrong lock!
- l.unlock();
- result = acquireLock(object, timeout, unit);
+ Lock lock = getLock(object);
+ if (lock.tryLock(timeout, unit))
+ {
+ // now check that the lock is still valid...
+ Lock currentLock = locks.putIfAbsent(object, lock);
+ if (currentLock != null && lock != currentLock)
+ {
+ // we acquired the wrong lock!
+ lock.unlock();
+ }
+ else
+ {
+ // we got the right lock!
+ return true;
+ }
+ }
+ else
+ {
+ // if we haven't acquired the lock (i.e., timed out) return false
+ return false;
+ }
}
- return result;
}
public void releaseLock(E object)
Show replies by date