Concurrent Programming 16--lock

Source: Internet
Author: User
Tags finally block

Java Concurrency Programming Practice Directory

Concurrent Programming 01--concurrenthashmap

Concurrent programming 02--blocking queues and producer-consumer patterns

Concurrent programming 03--latching countdownlatch and fence Cyclicbarrier

Concurrent programming 04--callable and future

Concurrent programming 05--completionservice:executor and Blockingqueue

Concurrent Programming 06--Task cancellation

Concurrent programming 07--interruption of task cancellation

Concurrent programming 08--task cancellation stop thread-based services

Concurrent programming 09--off of task cancellation Executorservice

Concurrent Programming 10--task cancellation "poison pill" object

Concurrent programming 11--Limitations of the shutdownnow of task cancellation and shutdown

Concurrent programming 12--use of the thread pool configuration threadpoolexecutor and Saturation policy

The overall architecture of the concurrent programming 13--thread pool

The principle of concurrent programming 14--thread pool

Two principles of concurrent programming 15--thread pool

Concurrent Programming 16--lock

Overview 1th part synchronized Defect 2nd Part Java.util.concurrent.locks Common Class 3rd part reference 1th part synchronized defect

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

If a block of code is synchronized decorated, when a thread acquires the corresponding lock and executes the block, the other threads can only wait 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.

The 2nd part of the Java.util.concurrent.locks package under the common class

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  lockinterruptibly () throws      interruptedexception;     boolean   Trylock ();  boolean  trylock (long  time,    Timeunit unit) throws   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:

1 Lock lock = ...; 2 Lock.lock (); 3 Try {4     // Processing Tasks 5 }catch(Exception ex) {6      7 }finally{  8     lock.unlock ();   // Release Lock 9 }

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:

1Lock lock = ...;2 if(Lock.trylock ()) {3      Try{4          //Processing Tasks5}Catch(Exception ex) {6          7}finally{8Lock.unlock ();//Release Lock9      } Ten}Else { One     //If you can't get the lock, do other things directly A}

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:

1  Public voidMethod ()throwsinterruptedexception {2 lock.lockinterruptibly ();3     Try {  4      //.....5     }6     finally {7 Lock.unlock ();8     }  9}

Note that when a thread acquires a lock, it is not interrupted by the interrupt () method. Because itself in the previous article, the separate call to the interrupt () method does not break the thread in the running process, only the threads in the blocking process can be interrupted.

Therefore, when a lock is acquired through the lockinterruptibly () method, it can be interrupted if it cannot be obtained and only waits.

And with synchronized modification, when a thread waits for a lock, it cannot be interrupted, only waiting.

  

2.ReentrantLock

Reentrantlock, which means "reentrant lock", describes the concept of reentrant locking in the next section. Reentrantlock is the only class that implements the lock interface, and Reentrantlock provides more methods. Here are some examples to see how to use Reentrantlock.

Example 1,lock () the correct way to use

1 /**2 * Lock () the correct way to use3 * @ClassName: Test4  * @authorXingle5 * @date 2015-1-7 pm 8:04:186  */7  Public classTest {8     PrivateArraylist<integer> ArrayList =NewArraylist<integer>();9 Ten      Public Static voidMain (string[] args) { One         FinalTest test =NewTest (); A         NewThread () { -              Public voidrun () { - Test.insert (Thread.CurrentThread ()); the             } - }.start (); -          -         NewThread () { +              Public voidrun () { - Test.insert (Thread.CurrentThread ()); +             } A }.start (); at     } -  -  -      Public voidInsert (Thread currentthread) { -Lock lock =NewReentrantlock ();//Watch this place . - Lock.lock (); in         Try{ -System.out.println (Currentthread.getname () + "Got the Lock"); to              for(inti=0;i<5;i++) { + Arraylist.add (i); -             } the}Catch(Exception ex) { *              $}finally{Panax NotoginsengSystem.out.println (Currentthread.getname () + "release lock"); - Lock.unlock (); the         } +          A     } the}

Execution Result:

3rd part Reference

1. "Java Concurrent Programming Combat" Chapter 13 shows the lock

2. Java Concurrency Programming: Lock

3. Locks in Java

4. Read/write locks in Java

5. "Java Concurrency Programming" 20: Concurrency new-lock lock and condition variable (with code)

6. Java Lock Summary

7. In-depth Java concurrency lock one

Concurrent Programming 16--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.