A Lock is a concurrency control class to support mutual exclusion. Some of
the additional functionality that is provided by this class w.r.t. synchronized
are :
- time out based lock acquiring semantics
- supports try lock semantics (isLocked())
- lock ownership can be determined (getOwner())
The usage pattern is the standard acquire/release protocol.
The usage of Lock can be see as under:
public class MyHashTable {
private Lock lock = new Lock();
.....
.....
public Object get(Key k) {
try {
lock.acquire()
....perform search to get the Object ...
} finally {
lock.release()
}
}
public Object set(Key k, Object o) {
try {
lock.acquire()
....perform operation to insert object ...
} finally {
lock.release()
}
}
}
This version of Lock also supports time out semantics when trying to acquire a
lock. If the lock is not acquired in the timeout parameter specified, a
TimedOutException is thrown. This would be extremely useful in avoiding deadlock
situations especially in I/O related multi-threaded access patterns.
This implementation of Lock is reentrant i.e. if the a thread that has a Lock
and tries to acquire the same lock, it would be given the lock
|