\file Lock .d \brief Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.

Written by Doug Lea with assistance from members of JCP JSR-166 Expert Group and released to the public domain, as explained at

http:
//creativecommons.org/licenses/publicdomain Ported to D by Ben Hinkle. Email comments and bug reports to ben.hinkle@gmail.com

revision 2.0 - ScopedLock suggested by Sean Kelly

  • interface Lock ;
  • \class Lock \brief Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.

    A lock is a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock.

    The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired.

    While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, some algorithms for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

    With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the automatic release of locks that occurs with synchronized methods and statements. In most cases, the following idiom should be used:

         Lock l = ...;
         l.lock();
         try {
             // access the resource protected by this lock
         } finally {
             l.unlock();
         }
    
    A ScopedLock can be used to simplify the above to
         Lock l = ...;
         auto ScopedLock sl = new ScopedLock(l);
         // access the resource protected by this lock
         // the lock will be release at the end of the block
    
    When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary.

    Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non-blocking attempt to acquire a lock using tryLock(), and an attempt to acquire the lock that can timeout tryLock(long, TimeUnit).

    A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection. If an implementation provides such specialized semantics then the implementation must document those semantics.

    Note that Lock instances are just normal objects and can themselves be used as the target in a synchronized statement. Acquiring the monitor lock of a Lock instance has no specified relationship with invoking any of the lock methods of that instance. It is recommended that to avoid confusion you never use Lock instances in this way, except within their own implementation.

    \see ReentrantLock \see Condition \see ReadWriteLock


  • abstract void lock ();
  • Acquires the lock .

    If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired.

  • abstract bool tryLock ();
  • Acquires the lock only if it is free at the time of invocation.

    Acquires the lock if it is available and returns immediately with the value true. If the lock is not available then this method will return immediately with the value false.

    A typical usage idiom for this method would be:

          Lock lock = ...;
          if (lock.tryLock()) {
              try {
                  // manipulate protected state
              } finally {
                  lock.unlock();
              }
          } else {
              // perform alternative actions
          }
    
    This usage ensures that the lock is unlocked if it was acquired, and doesn't try to unlock if the lock was not acquired.


    \return true if the lock was acquired and false otherwise.

  • abstract bool tryLock (long time, TimeUnit unit);
  • Acquires the lock if it is free within the given waiting time.

    If the lock is available this method returns immediately with the value true. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:

    • The lock is acquired by the current thread; or
    • The specified waiting time elapses

    If the lock is acquired then the value true is returned.

    If the specified waiting time elapses then the value false is returned. If the time is less than or equal to zero, the method will not wait at all.

    \param time the maximum time to wait for the lock \param unit the time unit of the time argument. \return true if the lock was acquired and false if the waiting time elapsed before the lock was acquired.


  • abstract void unlock ();
  • Releases the lock.

  • abstract Condition newCondition ();
  • Returns a new Condition instance that is bound to this Lock instance.

    Before waiting on the condition the lock must be held by the current thread. A call to Condition.wait() will atomically release the lock before waiting and re-acquire the lock before the wait returns.

    \return A new Condition instance for this Lock instance.

  • class ScopedLock ;
  • \class ScopedLock

    A wrapper around a lock which acquires the lock during construction and guarantees the lock is released at the end of the current scope. Use a ScopedLock when you need the Lock equivalent of synchronized statements. For example

     void example(Lock lock) {
       auto ScopedLock slock = new ScopedLock(lock); // acquires lock
       // the lock will be released at function exit
     }
    


    :: page rendered by CandyDoc