Display lock Reentrantlock and read-write lock for multi-threaded concurrent programming

Source: Internet
Author: User

Prior to Java5.0, only synchronized (built-in lock) and volatile. The display lock Reentrantlock is introduced after Java5.0.

Reentrantlock Overview

The Reentrantlock is a reentrant lock, which differs from the built-in lock, which needs to display the lock and unlock for each use, and provides more advanced features: Fair lock, timed lock, conditional lock, polling lock, interruptible lock. Can effectively avoid the deadlock of the active problem. Reentrantlock implements the

Lock interface:

   Public InterfaceLock {//block until a lock or interrupt is obtained          voidLock (); //block until a lock is acquired or an interrupt is thrown          voidLockinterruptibly ()throwsinterruptedexception; //only if the lock is available, or return directly          BooleanTrylock (); //only if the lock is available for a specified time, otherwise it is returned directly and throws an exception when interrupted          BooleanTrylock (LongTime, Timeunit unit)throwsinterruptedexception; voidunlock (); //returns a binding on the condition of this lockCondition newcondition (); }

Lock use

Lock lock =NewReentrantlock ();        Lock.lock (); Try{            //Update Object State}finally{            //note here that there must be a finally code block to unlock//Otherwise, it is easy to cause the deadlock and other active problemsLock.unlock (); }
Reentrantlock Characteristics Polling lock and timing lock

Polling and timing lock requests are implemented through the Trylock () method, unlike unconditional acquisition locks. Reentrantlock can have a flexible fault tolerance mechanism. Many of the deadlocks are caused by sequential locks, which are blocked by different threads as they attempt to acquire a lock, and do not release the locks they already hold, resulting in a deadlock. Trylock () method when attempting to acquire a lock, if the lock is already held by another thread, it is returned as set-up instead of blocking until the lock is released. You can retry or cancel based on the returned results, thereby avoiding the occurrence of deadlocks.

Fair sexboth fair and non-fair locks (default) are available in the Reentrantlock constructor. The so-called fair lock, the thread will be in the order in which they make the request to obtain the lock, do not allow queue jumping; But in the unfair lock, the queue is allowed: When a thread acquires a request for a lock, if the lock is available, the thread will skip the queue where it waits for the thread and get the lock. We generally hope that all locks are unfair. Because fairness, when performing a lock operation, will significantly degrade performance because of overhead when the thread hangs and resumes the thread. Consider a situation where a thread holds a lock and a B thread requests the lock, so the B thread is suspended, and a thread releases the lock, the B thread is awakened, and therefore attempts to acquire the lock, while the C thread requests the lock, the C thread is likely to get, use, and release the lock before the B thread is fully awakened. This is a win-wins situation, B acquires the lock moment (b is awakened to acquire the lock) and does not postpone, C acquires the lock earlier, and the throughput is improved. In most cases, the performance of a non-fair lock is higher than the performance of a fair lock. can be interrupted lock get operation The lockinterruptibly method can maintain a response to interrupts while acquiring a lock, so there is no need to create other types of non-disruptive blocking operations.   read/write lock Readwritelock

? Reentrantlock is a standard mutex that can hold a lock at most one thread at a time. Read-write locks are not the same, exposing two lock objects, one for read operations and the other for write operations.

  1.  public  interface   Readwritelock {  * Returns The lock used for reading.     * *   @return   The lock used for reading.     */  Lock Readlock ();      /**   * Returns the lock used for writing.     * *   @return   The lock used for writing.  */  Lock Writelock ();}  


you can choose to implement:
    • Release priority
    • Read Thread queue jump
    • Re-entry Sex
    • Downgrade
    • Upgrade
Reentrantreadwritelock implements the Readwritelock interface, and the constructor provides two ways to create fair and unfair locks. Read-write locks can be used for more than a few reads, enabling better concurrency.   Example
 Public classReadwritemap<k, v> {    PrivateMap<k, v>map; Private FinalReadwritelock lock =NewReentrantreadwritelock (); Private FinalLock Readlock =Lock.readlock (); Private FinalLock Writelock =Lock.writelock ();  PublicReadwritemap (Map<k, v>map) {         This. Map =map; }     PublicV get (K key) {Readlock.lock (); Try {            returnMap.get (key); } finally{readlock.unlock (); }    }     Public voidput (K key, V value) {Writelock.lock (); Try{map.put (key, value); } finally{writelock.unlock (); }    }}

Display lock Reentrantlock and read-write lock for multi-threaded concurrent programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.