Java re-entry lock Reentrantlock

Source: Internet
Author: User

This blog is turned around. but a little change thanks to http://my.oschina.net/noahxiao/blog/101558

Summary

From the perspective of the use of the scene to introduce the use of reentrantlock, relatively easy to understand some.

Scenario 1: If the operation is found to be executing, it is no longer executed (stateful execution)

A, when used on a scheduled task, if the task execution time may exceed the next scheduled execution time, ensure that the stateful task is only one executing, ignoring the duplicate trigger .
b, when you click on the interface to perform a long time request operation, prevent multiple clicks to cause the background to repeat ( ignoring the repeated trigger ).

The above two cases are used for non-important tasks to prevent recurrence, (such as: Clear unused temporary files, check the availability of some resources, data backup operations, etc.)

1 PrivateReentrantlockLock=NewReentrantlock ();2     3                 if(Lock. Trylock ()) {//if it is already locked, returns false immediately without waiting for the effect of ignoring the operation4  5                     Try {6  7                        //Operation8  9}finally {Ten                         Lock. Unlock (); One                     } A   -}
e.g such as a download button, after the click, before the resource is not available is not allowed to download two times. Scenario 2: If the operation is found to be executing, wait for the end to execute (synchronous execution, similar to synchronized)

This is a more common use, mainly to prevent the use of resources conflict, to ensure that only one operation can use the resource at the same time.
But the obvious difference from synchronized is the performance advantage (the gap that accompanies the JVM's optimization is decreasing). At the same time lock has a more flexible locking method, fair lock and unfair lock, and synchronized is always fair.

This situation is mainly used to scramble for resources (e.g. file operation, synchronous message sending, stateful operation, etc.)

Reentrantlock is not a fair lock by default

PrivateReentrantlockLock=NewReentrantlock ();//parameter default false, unfair lockPrivateReentrantlockLock=NewReentrantlock (true);//Fair Lock    Try {    Lock.Lock();//if it is locked by another resource, it will wait for the lock to be released to achieve a paused effect.//Operation } finally {    Lock. Unlock ();}

The difference between an unfair lock and a fair lock:

In a fair situation, the operation will queue up a team in order to ensure the order of execution. (Will consume more time to queue up)
In the unfair case, the unordered state allows queue jumping, and the JVM automatically calculates how to handle it faster to schedule a queue jump. (This is faster if you don't care about the order)

Scenario 3: If the operation is found to be already executing, try to wait for a period of time and wait for the timeout to not execute (try to wait for execution)

This is actually the improvement of scene 2, waiting for the lock operation to have a time limit, if the timeout is discarded execution.
Used to prevent deadlocks due to improper resource handling for long periods of time (everyone is waiting for resources, causing thread queues to overflow).

1   Try {2                     if(Lock. Trylock (5, Timeunit.seconds)) {//if it is already locked, try to wait for 5s to see if the lock can be obtained and return FALSE if the lock is still not available after 5s to continue execution3  4  5                         Try {6  7  8                             //Operation9  Ten   One}finally { A                             Lock. Unlock (); -                         } -   the   -                     } -}Catch(interruptedexception e) { -E.printstacktrace ();//when the current thread is interrupted (interrupt), it throws Interruptedexception +                 } -  
Scenario 4: If the operation is found to be executing, wait for execution. You can then interrupt the operation in progress to immediately release the lock and proceed to the next operation.

Synchronized and lock do not respond to the interrupt (interrupt) operation by default and will continue to execute. Lockinterruptibly () provides an interruptible lock to resolve this issue. (Another improvement in Scenario 2, no timeout, only waiting for interrupts or execution)

This situation is primarily used to cancel the use of resources by certain operations. such as: (Cancel the operation that is running synchronously to prevent the obstruction caused by the unhealthy operation for a long time)

Try {    lock. lockinterruptibly ();     // Operation  catch  (interruptedexception e) {    finally  {    lock  . Unlock ();}
Reentrant concept

If a program or subroutine can be "safely executed in parallel (Parallel computing)", it is referred to as reentrant (Reentrant or re-entrant). That is, when the subroutine is running, it can be re-entered and executed (in parallel execution, individual execution results meet design-time expectations). Reentrant concepts are presented in the era of single-threaded operating systems.

The main usage scenarios above are mainly about several methods that are often used in reentrantlock.

1, lock to obtain the lock, if the lock is in use then will wait.

2, lockinterruptibly obtain the lock, but the priority response is interrupted. During the waiting process, the interrupt is responded to.

3, Trylock () attempts to obtain a lock, if successful returns true. Otherwise do not wait, return immediately.

4, Trylock (long time,timeunit unit) attempts to acquire a lock within a given time.

5, Unlock () The release of the lock.

Java re-entry lock Reentrantlock

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.