Using Reentrantlock instead of synchronized keyword primitives in Java concurrency programming

Source: Internet
Author: User
Tags finally block

Tags: Java5introduced in the Concurrent Concurrency Library package, the Reentrantlock can be re-entered as a synchronous lock to replace the SYNCHRONIZED keyword primitives and provide better performance and more powerful functionality. The way to use it is simple: PublicFinal ReentrantlockLock=NewReentrantlock ();Try {    Lock.Lock(); //go to sync content    ....} finally {    Lock. Unlock ();//must be unlocked in the finally block, or it will remain locked in the event of an exception and no unlock is performed. The synchronized primitives and Reentrantlock are generally no different, but in very complex synchronization applications, consider using Reentrantlock, especially when you encounter the following 2 requirements. 1a thread needs to be interrupted while waiting for control of a lock2. Some wait-need to be handled separatelyNotify,reentrantlock inside of the condition application, able to control which thread notify3with the fair lock function, each incoming thread will be queued to say the first case, the Reentrantlock lock mechanism has 2 kinds, ignoring the interrupt lock and response interrupt lock, which gives us a lot of flexibility. For example: If a, B2 thread to compete lock, a thread get lock, b thread wait, but a thread this time really have too many things to deal with, is not return, B thread may be able to wait, want to interrupt themselves, no longer wait for this lock, to deal with other things. This time Reentrantlock provides 2 mechanisms, first, the B thread interrupts itself (or another thread interrupts it), but Reentrantlock does not respond, continue to let the B thread wait, how you interrupt, I am all one ear (synchronized the original language is so) Second, the B thread interrupts itself (or the other thread interrupts it), Reentrantlock handles the interrupt, and no longer waits for the lock to come and completely abandon it. (If you do not understand the Java interrupt mechanism, please refer to the relevant information, and then look back to this article, the%people do not really understand what is the interruption of Java, hehe) here to do a test, first of all to do a buffer class, it has read operations and write operations, in order not to read dirty data, write and read all need to lock, we first use synchronized primitive language to lock, as follows: Public classBuffer {PrivateObjectLock;  PublicBuffer () {Lock= This; }              Public voidwrite () {synchronized (Lock) {                LongStartTime =System.currenttimemillis (); System. out. println ("start writing data toward this buff ...");  for(;;)//simulation to be processed for a long time            {                    if(System.currenttimemillis ()-StartTime >integer.max_value) Break; } System. out. println ("finally finished ."); }        }              Public voidRead () {synchronized (Lock) {System. out. println ("read the data from this buff"); Then, let's define 2 threads, one thread to write, and one thread to read.  Public classWriter extends Thread {PrivateBuffer Buff;  PublicWriter (Buffer buff) { This. Buff =Buff; } @Override Public voidrun () {buff.write (); }         }          Public classReader extends Thread {PrivateBuffer Buff;  PublicReader (Buffer buff) { This. Buff =Buff; } @Override Public voidrun () {buff.read ();//It's probably going to clog up here .System. out. println ("Read End"); }} OK, write a main to test, we intentionally go to "write", and then let "read" Wait, "write" The time is endless, just see "read" can give up.  Public classTest { Public Static voidMain (string[] args) {Buffer buff=NewBuffer (); Final writer writer=NewWriter (Buff); Final Reader Reader=NewReader (Buff);            Writer.start ();                 Reader.start (); NewThread (NewRunnable () {@Override Public voidrun () {LongStart =System.currenttimemillis ();  for (;;) {                        //wait 5 Seconds to interrupt the read                    if(System.currenttimemillis ()-Start > the) {System. out. println ("wait, try to interrupt.");                            Reader.interrupt ();  Break;             }}}). Start (); }} We look forward to "read" This thread can exit the waiting lock, but it backfired, once read this thread found that they do not have a lock, it has been waiting, even if it is dead, there is no lock, because the write thread to 2.1 billion seconds to complete the t_t, even if we interrupt it, it does not respond, it seems really to die. At this time, Reentrantlock gave a mechanism for us to respond to interrupts, so that "reading" can stretch and give up the wait for the lock. Let's rewrite the buffer class, called bufferinterruptibly, which interrupts the cache.         Import Java.util.concurrent.locks.ReentrantLock;  Public classbufferinterruptibly {PrivateReentrantlockLock=NewReentrantlock ();  Public voidwrite () {Lock.Lock(); Try {                LongStartTime =System.currenttimemillis (); System. out. println ("start writing data toward this buff ...");  for(;;)//simulation to be processed for a long time            {                    if(System.currenttimemillis ()-StartTime >integer.max_value) Break; } System. out. println ("finally finished ."); } finally {                Lock. Unlock (); }        }              Public voidread () throws Interruptedexception {Lock. lockinterruptibly ();//Note here, you can respond to interrupts        Try{System. out. println ("read the data from this buff"); } finally {                Lock. Unlock (); }}} Of course, to respond to reader and writer changes Public classReader extends Thread {Privatebufferinterruptibly Buff;  PublicReader (bufferinterruptibly buff) { This. Buff =Buff; } @Override Public voidrun () {Try{buff.read ();//can receive an interrupt exception to effectively exit}Catch(interruptedexception e) {System. out. println ("I'm not reading."); } System. out. println ("Read End"); }         }              Public classWriter extends Thread {Privatebufferinterruptibly Buff;  PublicWriter (bufferinterruptibly buff) { This. Buff =Buff; } @Override Public voidrun () {buff.write (); }         }          Public classTest { Public Static voidMain (string[] args) {bufferinterruptibly buff=Newbufferinterruptibly (); Final writer writer=NewWriter (Buff); Final Reader Reader=NewReader (Buff);            Writer.start ();                 Reader.start (); NewThread (NewRunnable () {@Override Public voidrun () {LongStart =System.currenttimemillis ();  for (;;) {                        if(System.currenttimemillis ()-Start > the) {System. out. println ("wait, try to interrupt.");                            Reader.interrupt ();  Break;             }}}). Start (); This time the "read" thread received a lock.lockinterruptibly () interrupt and effectively handled the "exception". 

Java backend Framework source SPRINGMVC mybatis Oracle mysql maven HTML5 Bootstrap full new technology

Using Reentrantlock instead of synchronized keyword primitives in Java concurrency programming

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.