Coverage Report - org.jscsi.target.util.BinaryLock
 
Classes in this File Line Coverage Branch Coverage Complexity
BinaryLock
0%
0/10
0%
0/4
3
 
 1  
 package org.jscsi.target.util;
 2  
 
 3  
 
 4  
 import java.util.concurrent.locks.Lock;
 5  
 import java.util.concurrent.locks.ReentrantLock;
 6  
 
 7  
 
 8  
 /**
 9  
  * Instances of {@link BinaryLock} can be used to prevent concurrent access to the same resource, so, in essence, this
 10  
  * is a very simplified {@link Lock} implementation, however lacking many advanced capabilities.
 11  
  * <p>
 12  
  * A {@link BinaryLock} knows only two states, locked and unlocked. Attempts by the lock-holder to lock a
 13  
  * {@link BinaryLock} when locked or to unlock it when unlocked, will have no effect.
 14  
  * 
 15  
  * @author Andreas Ergenzinger
 16  
  */
 17  0
 public class BinaryLock {
 18  
 
 19  
     /**
 20  
      * The {@link ReentrantLock} which backs up the {@link BinaryLock} and takes care of suspending and notifying
 21  
      * waiting {@link Threads}.
 22  
      */
 23  0
     private final ReentrantLock lock = new ReentrantLock();
 24  
 
 25  
     /**
 26  
      * This method is used to acquire the lock. It will block until no other {@link Thread} is holding the lock and then
 27  
      * return <code>true</code> to indicate the successful lock acquisition, or return <code>false</code>, if the
 28  
      * calling {@link Thread} was interrupted while waiting for the lock.
 29  
      * <p>
 30  
      * If the caller is already holding the lock, the method will immediately return <code>true</code> without any
 31  
      * changes.
 32  
      * 
 33  
      * @return <code>true</code> if and only if the lock has been acquired
 34  
      */
 35  
     public boolean lock () {
 36  
         try {
 37  0
             lock.lockInterruptibly();
 38  0
             return true;
 39  0
         } catch (InterruptedException e) {
 40  0
             return false;
 41  
         }
 42  
     }
 43  
 
 44  
     /**
 45  
      * Releases the lock when called by the current lock holder;
 46  
      */
 47  
     public void unlock () {
 48  0
         if (lock.isHeldByCurrentThread()) {
 49  0
             while (lock.getHoldCount() > 0)
 50  0
                 lock.unlock();
 51  
         }
 52  0
     }
 53  
 
 54  
 }