Java threading and concurrent programming practices----LOCK frames

Source: Internet
Author: User

The Java.util.concurrent.locks package provides a framework that contains a variety of interfaces and classes that

Lock and wait on the condition. Unlike object's built-in lock synchronization and Java.lang.Object

The wait/notify mechanism, the Concurrency tool class that contains the lock framework improves this by polling locks, display waits, and other methods

Mechanism.

The lock frame contains categories such as frequently used locks, re-entry locks, conditions, read and write locks, and read and write locks.

Locks (Lock)

The lock implementation provides a wider range of locking operations than is possible with synchronized methods and statements. This real

Now allows for a more flexible structure that can have very different properties and can support multiple related Condition objects.

A lock is a tool that controls the access of multiple threads to a shared resource. Typically, a lock provides exclusive access to a shared resource.

Only one thread can get a lock at a time, and all access to the shared resource requires a lock first. However, some locks

May allow concurrent access to shared resources, such as read locks for Readwritelock.

The use of the Synchronized method or statement provides access to the implicit monitor lock associated with each object, but

Forcing all lock acquisition and deallocation to occur in a block structure: When multiple locks are acquired, they must be in the opposite

Released in order, and all locks must be released in the same lexical scope as all locks are fetched.

Although the scope mechanism of the synchronized methods and statements makes it much easier to program with monitor locks, it also

Help avoids a lot of common programming errors involving locks, but sometimes you need to use locks in a more flexible way.

For example, some algorithms that traverse the data results of concurrent access require the use of "Hand-over-hand" or "Chain locking":

Get the lock for node A, then get the lock for node B, then release A and get C, and then release

B and get D, and so on. The implementation of the lock interface allows the lock to be acquired and released within different scopes,

and allows multiple locks to be acquired and freed in any order, thereby supporting the use of this technique.

Second, re-enter the lock

The class Reentrantlock implements an interface lock, which describes a reentrant mutex. This lock and a holding volume

Associated. When a thread holds this lock and calls lock (), lockuninterruptibly () or any one of the Trylock ()

method to regain the lock, the holding amount is incremented by one. When the thread calls the Unlock () method, the holding amount is decremented by 1. When holding volume

Drop to zero and the lock will be released.

Reentrantlock provides the same concurrency semantics as a hermit listener lock accessed through a synchronous method, code block

and memory semantics. However, it has extensible functionality and in a high thread contention environment (threads frequently request access to already

Locks held by other threads) have better performance.

To implement a synchronization block using a re-enter lock:

 import java.util.concurrent.executorservice;import java.util.concurrent.executors;import  java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;public class  Test {public static void main (String[] args)  {final lock lock =  new reentrantlock (); Executorservice execute = executors.newfixedthreadpool (2); class worker implements  runnable {private final string name;public worker (String name)  { This.name = name;} @Overridepublic  void run ()  {lock.lock (); System.out.println (Thread.CurrentThread (). GetName ()  + "---" + name); try {thread.sleep (1000);}  catch  (interruptedexception e)  {e.printstacktrace ();}  finally {lock.unlock ();}}} Execute.execute (New worker ("Jiaxx")) Execute.execute (New worker ("Jiadd")); Execute.shutdown ();}} 

Third, conditions

The condition interface decomposes the wait and notification methods of object into different conditional objects.

By combining these conditions with the use of any lock implementation, it is possible to have multiple wait sets on each object

's role. Here lock replaces the synchronization method, the code block, condition replaces the object's wait, notification

Method.

Use re-entry locks and conditions to implement producers and consumers:

package xiancheng;import java.util.concurrent.locks.condition;import  Java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;public class pc  {public static void main (String[] args)  {Shared s = new  GKFX (); Thread t1 = new thread (New product (s,s.lock,s.condition)); Thread t2 = new thread (New consumer (s,s.lock,s.condition)); T1.start (); T2.start ();}} class shared {private char c;private volatile boolean writeable =  true;final lock lock;final condition condition;public shared ()  {this.lock  = new reentrantlock (); This.condition = lock.newcondition ();} Public void setchar (Char ch)  {lock.lock ();while  (!writeable)  {try { Condition.await ();}  catch  (interruptedexception e)  {e.printstacktrace ();}} ThiS.c = ch;writeable = false;condition.signal (); Lock.unlock ();} Public char getchar ()  {lock.lock ();while  (writeable)  {try {condition.await ();  catch  (interruptedexception e)  {e.printstacktrace ();}} Writeable = true;condition.signal (); Lock.unlock (); return c;}} class product implements runnable {private final shared s;private  Final lock lock;private final condition condition;public product (Shared s,  lock lock, condition condition)  {this.s = s;this.lock = lock; This.condition = condition;} @Overridepublic  void run ()  {for  (char i =  ' A '; i <  ' Z ';  i++)  {lock.lock (); S.setchar (i); System.out.println ("producer produces a"  + i); Lock.unlock ();}} Class consumer implements runnable {private final lock lock;private final condition condition;private final shared s;public  Consumer (shared s, lock lock, condition condition)  {this.s = s; This.lock = lock;this.condition = condition;} @Overridepublic  void run ()  {char ch;do {lock.lock (); Ch = s.getchar (); SYSTEM.OUT.PRINTLN ("Consumer consumes a"  + ch); Lock.unlock ();}  while  (ch !=  ' Z ');}}

Iv. Read and write locks

Read-write locks are suitable for scenarios where data structures are read frequently and less modified.

The lock framework provides a read-write lock mechanism for these scenarios, with better concurrency when reading, and when writing

Ensure secure, mutually exclusive access. This mechanism is based on an interface Readwritelock interface. The interface maintains a pair of locks, a

For write operations, a read lock can be held by multiple threads for a read operation, while a write lock is mutually exclusive, allowing only one thread

Access to modify shared data.

Implementation of the specific code see my other Weibo blog:

http://blog.51cto.com/12222886/1964183

Java threading and concurrent programming practices----LOCK frames

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.