Java Lock Learning

Source: Internet
Author: User

Individual learning to organize, all the information from the network, non-original.

The four necessary conditions for a deadlock:
Mutex condition (Mutual exclusion): A resource cannot be shared and can only be used by one process.
Request and hold condition (holds and wait): a process that has already received a resource can request a new resource again. When a process is blocked by requesting a resource, it remains in place for the resources that have been obtained.
Non-deprivation condition (no pre-emption): The allocated resources cannot be forcibly stripped from the corresponding process.
Cyclic wait condition (Circular wait): Several processes in the system make up loops in which each process waits for resources that are being consumed by neighboring processes.

It is not difficult to see that the second to third and four conditions are more easily eliminated in the four prerequisites for deadlock. By introducing a transaction mechanism, it is often possible to eliminate the second to third two conditions by treating all locking operations as transactions and, once the lock is started, to ensure that all operations can be rolled back, while detecting deadlocks through the lock manager and depriving resources (fallback transactions). This is sometimes a costly exercise and requires more changes to the lock mode.

The elimination of the fourth condition is an easier and less costly approach. Specifically, this approach is agreed: the order of locking must be the same. Specifically, we artificially assign a lock to a directional property similar to "water level". Regardless of whether a lock is held, all the locking operations of the thread must be carried out in a consistent sequence from low to high (or high to low), and only one order of precedence is allowed in a system.

Note that the order in which locks are placed does not cause deadlocks. In other words, although it may seem strange to follow the order of lock A, lock B, put A and B, it will not cause a deadlock, as long as everyone is locked in the order of first A and B.

Avoid the deadlock algorithm, the banker algorithm, wait until there is time, then to study it.

Again, the reentrant nature of the Lock:

Each lock is associated with a request counter and a thread that occupies him, and when the request counter is 0 o'clock, the lock can be considered unhled, when a thread requests a unheld lock, the JVM records the lock's owner, and the lock request count is incremented by 1, if the same thread requests the lock again, The request counter is incremented, and when the thread exits the syncronized block, the counter is reduced by 1 and the lock is released when the counter is 0 o'clock.

Based on these analyses, the following is a summary of the differences between synchronized and Reentrantlock, as follows:

1. In the event of an exception, the synchronized lock, the JVM will be recycled,

The re-entry concept is:

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 reentrant mechanism of the lock can be used to solve the following problem:

 public  class   Widget { public  synchronized void   DoSomething () {...}  public  class   Loggingwidget extends Widget { public  synchronized void   DoSomething () {System.  out . println (toString () +  : Calling dosomething   " );      Super.dosomething (); }  }

Without the reentrant nature of the Java lock, when a thread acquires a lock on Loggingwidget's dosomething () block of code, the thread has already got the lock of the Loggingwidget, when the DoSomething () method in the parent class is called, The JVM will assume that the thread has acquired a loggingwidget lock, and cannot retrieve it again, so that it cannot invoke the widget's DoSomething () method, thereby shining a deadlock. As we can see from this, Java threads are based on "per-thread (per-thread)" rather than "per-call (per-invocation)", meaning that Java assigns a lock to each thread instead of assigning a lock to each call.

A lock can be re-entered, and when the lock is not owned by another thread, the thread that called lock succeeds in acquiring the lock and returning it. If the current thread already owns the lock, this method will return immediately. You can use the Isheldbycurrentthread () and Getholdcount () methods to check whether this condition occurs.

For a reentrant lock, one thing to understand is to note:

while the thread is Waiting (con.await), the lock is no longer owned (keep), so the other threads can get a re-entry lock.

It is necessary to take a look at the official Java explanation: "If the lock is persisted by another thread, the current thread is disabled for the purpose of thread scheduling and the thread will remain dormant until the lock is acquired." My understanding of the "hold" here refers to all States outside the wait state, such as thread sleep, for loops, and everything that has CPU involvement. Once the thread enters the wait state, it no longer keep the lock, and the other thread can obtain the lock, and when the thread is awakened (triggering a signal or timeout), it is then executed, which will re-"hold" the lock, although the other thread is no longer "holding" the Re-entry lock.

For this, I think it can be understood that synchronized and Reentrantlock are both reentrant, and wait will release the lock.

One such scenario is the delay queue delayqueue, such as Take (), for the implementation of task scheduling in Java concurrent . The main function of this method is to remove a task (optimal value) from the priority queue (Priorityqueue) that should be performed, if the task's subscription execution time is not reached, then the wait time is poor. Conversely, if the time is up, the task is returned. The offer () method is to add a task to the queue. (This is a very useful feature to write a demo code for this function when you are free)

Then there was a question: what would happen if the most likely task was to be performed after one hours, and a task to be executed after 10 seconds was required? Will you wait until the take () is returned before you can submit it?

The answer is no, because take () and offer () all use the mechanism of a reentrant lock, which is indeed a non-blocking lock. There is an await () operation in the middle.

Re-entry Lock usage scenarios:

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.)

Private New Reentrantlock (); if (Lock.trylock ()) {  //                     try  {                        /  / action                       Finally  {                        lock.unlock ();                    }                 }

Learning from Java locks

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.