Java Concurrency Programming: Lock

Source: Internet
Author: User
Tags key case ming

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 thread waits until the thread that acquires the lock releases the lock, and there are three 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.

3) This is mainly waiting for the wake-up mechanism of the wait () method,//In the waiting time immediately release the lock, convenient for other threads to use the lock. And when it wakes up, it wakes up here,

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. So we need to make it easier for other threads to execute regardless of how the program's code block ultimately frees the lock object. (Here is a simple demo starting from the manual release of the lock object and the execution in the finally)

While we can understand the problem of locking objects for synchronous blocks and synchronous methods, we do not see directly where the lock is added, where the lock is released, and in order to release the lock better.
In order to express more clearly how to lock and release the lock, JDK5 later provided a new lock object 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) Synchronized is implemented at the JVM level, not only through some monitoring tools to monitor the synchronized lock, but also when the code executes an exception, the JVM will automatically release the lock, but not with lock , Lock is implemented by code, and to ensure that the lock is guaranteed to be released, the Unlock () must be placed in the finally{}

3) In the case of resource competition is not very intense, synchronized performance is better than Reetrantlock, but in the case of fierce competition in resources, synchronized performance will be reduced dozens of times times,

But Reetrantlock performance can maintain the normal;
First, give a simple self-locking case, mainly for the realization of self-locking occurs can be
Split Line for------------------------------------------------code
First a deadlock case is given. The first class is: MyLock
1  Public class MyLock {2     // to create two lock objects 3      Public Static Final New Object (); 4      Public Static Final New Object (); 5 }

The thread where the deadlock occurred

1  Public classDielockextendsThread {2 3     Private BooleanFlag;4 5      PublicDielock (Booleanflag) {6          This. Flag =Flag;7     }8 9 @OverrideTen      Public voidrun () { One         if(flag) { A             synchronized(mylock.obja) { -System.out.println ("If Obja"); -                 synchronized(MYLOCK.OBJB) { theSystem.out.println ("If OBJB"); -                 } -             } -}Else { +             synchronized(MYLOCK.OBJB) { -System.out.println ("Else OBJB"); +                 synchronized(mylock.obja) { ASystem.out.println ("Else Obja"); at                 } -             } -         } -     } -}

Deadlock Test Demo

1 /*2 * The drawbacks of synchronization:3 * A: Low efficiency4 * B: Easy to create deadlocks5  * 6 * Deadlock:7 * Two or more threads in the process of contention for resources, the occurrence of a mutual waiting phenomenon. 8  * 9 * Examples:Ten * Xiao Ming and Xiao Qiang's bikes have two locks. One key case.  One * Normal situation: A * Xiao Ming: There are two keys to the lock; - * Jack Bauer: There are two keys to the lock.  - * Now: the * Xiao Ming: Two keys with one of the locks; - * Jack Bauer: Two keys with another lock.  - * Ending two people can not open the lock .... Waiting for the night to get out of the bike -  */ +  Public classDielockdemo { -      Public Static voidMain (string[] args) { +Dielock DL1 =NewDielock (true); ADielock DL2 =NewDielock (false); at  - Dl1.start (); - Dl2.start (); -     } -}

//============================================

Second, the lock lock simple use
1 ImportJava.util.concurrent.locks.Lock;2 ImportJava.util.concurrent.locks.ReentrantLock;3 4  Public classSellticketImplementsRunnable {5 6     //Define Tickets7     Private intTickets = 100;8 9     //Defining Lock ObjectsTen     PrivateLock lock =NewReentrantlock (); One  A @Override -      Public voidrun () { -          while(true) { the             Try { -                 //Locking - Lock.lock (); -                 if(Tickets > 0) { +                     Try { -Thread.Sleep (100); +}Catch(interruptedexception e) { A e.printstacktrace (); at                     } - System.out.println (Thread.CurrentThread (). GetName () -+ "Selling" + (tickets--) + "Ticket"); -                 } -}finally { -                 //Release Lock in Lock.unlock (); -             } to         } +     } -  the}

Here is the test class
1  Public classRunnabledemo {2      Public Static voidMain (string[] args) {3Sellticketsrunnable str =Newsellticketsrunnable ();4         5Thread TR1 =NewThread (str, "Window 1");6Thread TR2 =NewThread (str, "Window 2");7Thread TR3 =NewThread (str, "Window 3");8         9         //Ten Tr1.start (); One Tr2.start (); A Tr3.start (); -     } -}



Java Concurrency Programming: 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.