Java Concurrency Programming: Lock

Source: Internet
Author: User
Tags finally block

In the previous article we talked about how to use the keyword synchronized to achieve synchronous access. In this article we continue to explore this issue, from Java 5, under the Java.util.concurrent.locks package provides another way to achieve synchronous access, that is, lock.

Perhaps a friend will ask, since all can be synchronized to achieve synchronous access, then why do you need to provide lock? This question will be described below. This article starts with the defect of the synchronized, and then narrates what classes and interfaces are commonly used under the Java.util.concurrent.locks package, and finally discusses some of the following concepts about locks

The following is an outline of this article directory:

I. Deficiencies of the synchronized

Two. Java.util.concurrent.locks under the common class

Three. Introduction to the relevant concept of lock

If there are any shortcomings please understand, and welcome criticism.

Please respect the author's labor results, reproduced please indicate the original link:

Http://www.cnblogs.com/dolphin0520/p/3923167.html

I. Deficiencies of the synchronized

Synchronized is a keyword in Java, which is a feature built into the Java language. So why is there lock?

In the previous article, we learned that if a block of code is synchronized, when a thread acquires the corresponding lock and executes the block, the other thread waits until the thread that acquires the lock releases the lock, and there are only two cases where the thread that acquires the lock releases the lock:

1) The thread that acquires the lock executes the code block, and then the thread releases the possession of the lock;

2) A thread execution exception occurs when the JVM causes the thread to automatically release the lock.

So if the thread that acquires the lock is blocked by waiting for IO or other reasons (such as calling the Sleep method), but the lock is not released, the other threads can only wait in a dry way, and imagine how this affects the execution efficiency of the program.

There is therefore a need for a mechanism to allow waiting threads to wait indefinitely (for example, to wait for a certain amount of time or to respond to interrupts), which can be done with lock.

Another example: when there are multiple threads reading and writing files, there is a conflict between read and write operations, and write operations and writes conflict, but there is no conflict between read and read operations.

But using the Synchronized keyword to achieve synchronization can cause a problem:

If multiple threads are simply reading, other threads can only wait for the read operation when one thread is reading.

Therefore, a mechanism is needed to enable multiple threads to simply read, and there will be no conflicts between threads, which can be done by lock.

Additionally, through lock you can know that the line threads has not been successfully acquired to the lock. This is synchronized can't do.

To summarize, this means that lock provides more functionality than synchronized. But pay attention to the following points:

1) lock is not built into the Java language, synchronized is a keyword in the Java language and is therefore a built-in feature. Lock is a class that enables simultaneous access through this class;

2) lock and synchronized a very big difference, the use of synchronized does not require the user to manually release the lock, when the synchronized method or synchronized code block execution, the system will automatically let the thread release the lock on the use of , and lock must be the user to manually release the lock, if there is no active release of the lock, it is possible to cause a deadlock phenomenon.

Two. Java.util.concurrent.locks under the common class

Let's explore the classes and interfaces commonly used in java.util.concurrent.locks packages.

 1.Lock

The first thing to illustrate is lock, by looking at the source of the lock is known, lock is an interface:

 Public Interface Lock {    void  lock ();     void throws interruptedexception;     Boolean Trylock ();     boolean trylock (longthrows  interruptedexception;     void unlock ();    Condition newcondition ();}

The following describes the use of each method in the lock interface individually, lock (), Trylock (), Trylock (long time, Timeunit unit), and lockinterruptibly () are used to acquire the lock. The UnLock () method is used to release the lock. Newcondition () This method is not described here for the moment, and will be described in the following thread collaboration article.

Four methods are declared in lock to acquire a lock, so what is the difference between the four methods?

First, the lock () method is the most commonly used method, which is used to acquire a lock. Waits if the lock has been fetched by another thread.

As mentioned earlier, if you use lock, you must voluntarily release the lock, and the lock will not be released automatically when an exception occurs. Therefore, in general, the use of lock must be done in the try{}catch{} block, and the operation to release the lock is placed in the finally block to ensure that the lock must be released to prevent the occurrence of deadlocks. The use of lock for synchronization is usually done in the following form:

Lock lock = ...; Lock.lock (); Try {    // Processing Task }catch(Exception ex) {     }finally{    Lock.unlock ();    // release Lock }

The Trylock () method is a return value that represents the attempt to acquire a lock, returns true if it succeeds, or false if the fetch fails (that is, the lock has been fetched by another thread), which means that the method returns immediately anyway. You won't be waiting there until you get the lock.

The Trylock (long time, Timeunit unit) method and the Trylock () method are similar except that the method waits for a certain amount of time when the lock is not reached, and returns False if the lock is not held within the duration of the period. Returns true if the lock was obtained at the beginning or if the lock was obtained during the wait period.

So, in general, the use of trylock to acquire locks is as follows:

 lock lock = ...;  if   (Lock.trylock ()) { try  {  Processing task }catch   (Exception ex) {}  finally{Lock.unlock ();       //  release lock   else   { //  If you can't get the lock, do something else } 

The lockinterruptibly () method is special, and when the lock is acquired by this method, if the thread is waiting to acquire the lock, the thread can respond to the interrupt, that is, the wait state of the break thread. It is also said that when two threads pass through lock.lockinterruptibly () to acquire a lock, if thread A acquires a lock at this point, and thread B is only waiting, then the call to thread B of the Threadb.interrupt () method can be used in the wait process of break thread B.

Because an exception was thrown in the declaration of Lockinterruptibly (), lock.lockinterruptibly () must be placed in a try block or in a call to lockinterruptibly () Out-of-method declarations throw interruptedexception.

Lockinterruptibly () is therefore generally used in the following form:

 Public void throws interruptedexception {    lock.lockinterruptibly ();     Try  {       //.....     }    finally  {        lock.unlock ();    }  }

The rest: http://www.cnblogs.com/dolphin0520/p/3923167.html

Java Concurrency Programming: Lock

Related Article

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.