Java Multi-threaded re-entry lock

Source: Internet
Author: User
Tags ming ticket

as a substitute for the keyword synchronized (or enhanced version), the re-entry lock is a function extension of the synchronized. in earlier versions of JDK 1.5, the ability to re-enter locks was much better than synchronized, but since JDK 1.6, the JDK has optimized the synchronized, making the performance gap between the two less significant. The re-entry lock is implemented using the Java.util.concurrent.locks.ReentrantLock class.

Using a locking lock allows you to specify when and when to release a lock, which is much better than synchronized for logical control and must be released when you exit the critical section. This is called a re-entry lock because a thread can obtain the lock continuously.

The simple re-entry lock use example is as follows:

  

Modify the above code 第7-12 line:

  

In this case, a thread gets the same lock two times in a row. If the operation is not allowed, the same thread will generate a deadlock with itself on the 2nd request for a lock, and the program dies during the 2nd request for a lock. If the same thread obtains the lock more than once, the lock is released the same number of times. If the number of locks is released, then there is a java.lang.IllegalMonitorStateException exception, and conversely, if the number of times the lock is released, the thread still holds the lock.

In addition to the flexibility used, the re-entry lock provides some advanced features:

1 Interrupt Response

For synchronized, if a thread waits for a lock, there are only two possible results: either get the lock to continue execution or wait. The use of a re-entry lock can provide another possibility: the thread can be interrupted. In other words, the thread waits for the lock, and the program can cancel the lock request as needed. For example, Xiao Wang and Xiao Ming go to play ball, if Xiao Wang waited for 10 minutes, Xiaoming has not arrived, received Xiao Ming's telephone to understand that because of unexpected circumstances can not be as promised, then the small Wang will be disappointed to go home. For threads, if a thread is waiting for a lock, it can receive a notification that it can stop working without waiting. This situation can be helpful in dealing with deadlocks.

2 Lock request Wait time limit

In addition to waiting for external notifications, there is another way to avoid deadlocks: time-limited waiting. Continue the above example, if Xiao Wang waited for half an hour, Xiao Ming still does not come, then the small Wang is disappointed to leave. For a thread, if a wait time is given and the thread is automatically discarded, the thread can be prevented from continuing to wait.

3 Fair Lock

In most cases, the lock application is unfair. That is, thread 1 first applied for lock A, then thread 2 also applied for lock A, then when the lock A is available, which thread obtains the lock is not necessarily, the system will be selected from the waiting queue of lock a randomly, does not guarantee fairness. As if the ticket does not line up, we all noisy around the ticket window, the conductor busy, who do not want who first who, casually find a person out of the ticket on the finished. The fair lock guarantees a first-come-first-served, no starvation. As long as the team is lined up, resources can eventually be obtained. The lock generated by synchronized is not fair, and the re-entry lock can be set to be fair. The re-entry lock requires the system to maintain an orderly queue, which is cost-efficient and low-performance. Therefore, the lock by default is unfair.

The common methods of the Reentrantlock class are as follows:

1 Public Reentrantlock (Boolean fair)

When the parameter fair is true, it indicates that the re-entry lock is fair.

2 Lock ()

Gets the lock and waits if the lock is already occupied.

3 lockinterruptibly ()

Gets the lock, but the priority response is interrupted.

4 Trylock ()

Tries to get the lock, returns true if successful, otherwise returns false. The method does not wait and returns immediately.

5 Trylock (long time, timeunit unit)

Attempts to acquire a lock within a given time.

6 unlock ()

Release the lock.

The implementation of a reentrant lock consists of 3 elements:

1 atomic states

Atomic states use CAS operations to store the state of the current lock and determine if the lock has been held by another thread.

2 Waiting queue

All threads that do not acquire a lock go into the wait queue to wait. When the lock is released by a thread, the system wakes up from the waiting queue and continues to work.

3 Blocking Primitives Park () and Unpark ()

Pending and resuming threads, threads that are not acquired to the lock are suspended.

  

Resources

"Practical Java High concurrency program design" p71-80

Java Multi-threaded re-entry lock

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.