gov.sns.tools
Class Lock

java.lang.Object
  |
  +--gov.sns.tools.Lock

public class Lock
extends java.lang.Object

Lock allows an alternative method to Java's synchronize feature for locking resources from other threads. The reason for this alternative is to provide the ability to test for a lock without waiting. Lock has methods for both waiting for a lock and testing for a lock. If a lock is held by the same thread requesting it, the lock is immediately granted. Every lock must be balanced by a call to unlock(). The lock is freed only when all locks have been relinquished.


Constructor Summary
Lock()
          Creates a new instance of Lock
 
Method Summary
 boolean lock()
          Request a lock and wait until the lock is granted.
 boolean tryLock()
          Try to get a lock.
 void unlock()
          Relinquish the lock.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Lock

public Lock()
Creates a new instance of Lock

Method Detail

lock

public boolean lock()
Request a lock and wait until the lock is granted. If the request comes from the same thread holding the lock, this method simply increments the lock count and grants the lock immediately. Every call to this method must be balanced with a call to unlock() to relinquish the lock.

Returns:
true if the lock has been granted and false if the lock failed
See Also:
unlock()

unlock

public void unlock()
Relinquish the lock. This method must be called by the same thread that currently holds the lock.


tryLock

public boolean tryLock()
Try to get a lock. If the request is successful then hold the lock. Whether or not the request is successful, this method will always return immediately. Every call to this method that is successful (and only those that are successful) should be balanced by a call to unlock. A typical call looks like:
if( lock.tryLock() ) {
// some code here...
lock.unlock();
}

Returns:
true if the lock was successful and false otherwise.