Java Reentranlock Lock

Source: Internet
Author: User
Tags finally block mutex

1, the effect and synchronized, can be executed synchronously, lock method to obtain the lock, unlock method release lock

Examples of Use:

 Packagecom.test;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classMyService {PrivateLock lock =NewReentrantlock ();  Public voidMethodA () {Try{lock.lock (); System.out.println ("MethodA Begin ThreadName =" + Thread.CurrentThread (). GetName () + "time=" +System.currenttimemillis ()); Thread.Sleep (3000); System.out.println ("MethodA End threadname =" + Thread.CurrentThread (). GetName () + "time=" +System.currenttimemillis ()); } Catch(Exception e) {e.printstacktrace (); } finally{lock.unlock (); }    }         Public voidMethodB () {Try{lock.lock (); System.out.println ("MethodB Begin ThreadName =" + Thread.CurrentThread (). GetName () + "time=" +System.currenttimemillis ()); Thread.Sleep (3000); System.out.println ("MethodB End threadname =" + Thread.CurrentThread (). GetName () + "time=" +System.currenttimemillis ()); } Catch(Exception e) {e.printstacktrace (); } finally{lock.unlock (); }    }}
 Packagecom.test; Public classRun { Public Static voidMain (string[] args) {MyService MyService=NewMyService (); Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {Myservice.methoda ();        }        }); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () {myservice.methodb ();        }        });        T1.start ();    T2.start (); }}
= Thread-0time =1527821296840= Thread-0time =1527821299841= Thread-1time =1527821299841= Thread-1time =1527821302841

Note: You must call the Lock.unlock () release lock in the finally block.

2. Use condition to implement wait/notification:

Awati () and Signal () method:

  

 Packagecom.test;Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classMyService {PrivateLock lock =NewReentrantlock (); PrivateCondition Condition =lock.newcondition ();  Public voidtestwait () {Try{lock.lock (); System.out.println ("Wait");        Condition.await (); } Catch(Exception e) {e.printstacktrace (); } finally{lock.unlock (); }    }         Public voidtestsignal () {Try{lock.lock ();        Condition.signal (); } finally{lock.unlock (); }    }    }
    • By condition an object to wait for a thread, you must first execute Lock.lock () to obtain the lock.
    • The signal () method of the condition object can wake the thread.
    • The Awati () method of condition is equivalent to the Wati () method in object.
    • The signal () method of condition is equivalent to the Notify () method in object.
    • The Signalall () method of condition is equivalent to the Notifyall () method in object.

3, fair lock and non-fair lock:

A fair lock identifies the order in which threads acquire locks in the order in which they are Cheng in line. First-come first-served FIFO first-out order. The non-fair lock is a preemption mechanism for acquiring locks, and it is a random acquisition of locks.

  

Lock lock=New reentrantlock (true); // Fair Lock Lock lock=New Reentrantlock (false); // Non-fair lock

4, the method of Reentrantlock class:

    • The function of int getholdcount () is to query the number of times that the current thread holds this lock, that is, the number of calls to the lock () method.
    • The use of int getqueuelength () is to return the estimated number of threads that are waiting to acquire this lock. For example, there are 5 threads, and 1 threads first execute the await () method, then the return value of calling this method is 4.
    • The use of int getwaitqueuelength (Condition Condition) is to return the thread estimates for the Condition of the given condition associated with this lock, such as 5 threads that have executed the Condition await () method, Then the return value is 5.
    • The function of Boolean hasqueuedthreads () is to query whether a thread is waiting to acquire this lock.
    • The role of Boolean haswaiters (Condition Condition) is to query whether a thread is waiting for the Condition condition associated with this lock.
    • The function of the Boolean Isfair () is to judge whether the lock is fair.
    • The function of Boolean isheldbycurrentthread () is to query whether the current thread holds this lock.
    • The function of Boolean isLocked () is to query whether this lock is persisted by any thread.
    • void lockinterruptibly () has the effect of acquiring a lock if the current thread is not interrupted, or an exception if it has been interrupted.
    • The purpose of Boolean trylock () is to obtain the lock only if the lock is not persisted by another thread at the time of the call.
    • The function of the Boolean trylock (long timeout, timeunit unit) is to obtain the lock if the lock is not held by a thread within a given wait time and the current thread is not interrupted.

5, Reentrantreadwritelock class, read and write lock:

The class Reentrantlock has a completely mutex exclusive effect, that is, only one thread at a time executes the task after the lock () method.

The read-write lock indicates that there are also two locks, one is a read-related lock, also a shared lock, and the other is a write-related lock, which also locks the lock. That is, multiple read locks are not mutually exclusive, the read lock is mutually exclusive to the write lock, and the write lock is mutually exclusive. When there is no thread to write, the read lock can be obtained by multiple threads for the read operation, and the thread that writes the operation cannot write until the write lock is acquired. That is, multiple threads can read at the same time, but only one thread can write at the same time.

    • Read share

  

    PrivateReentrantreadwritelock lock =NewReentrantreadwritelock ();  Public voidRead () {Try {            Try{lock.readlock (). Lock (); System.out.println ("Get read lock:" +System.currenttimemillis ()); Thread.Sleep (1000); } finally{lock.readlock (). Unlock (); }        } Catch(Exception e) {e.printstacktrace (); }    }
    • Write-Write Mutex

  

    PrivateReentrantreadwritelock lock =NewReentrantreadwritelock ();  Public voidwrite () {Try {            Try{lock.writelock (). Lock (); System.out.println ("Get write Lock:" +System.currenttimemillis ()); Thread.Sleep (1000); } finally{lock.writelock (). Unlock (); }        } Catch(Exception e) {e.printstacktrace (); }    }
    • Read-Write Mutex

  

    PrivateReentrantreadwritelock lock =NewReentrantreadwritelock ();  Public voidRead () {Try {            Try{lock.writelock (). Lock (); System.out.println ("Get read lock:" +System.currenttimemillis ()); Thread.Sleep (1000); } finally{lock.writelock (). Unlock (); }        } Catch(Exception e) {e.printstacktrace (); }    }         Public voidwrite () {Try {            Try{lock.writelock (). Lock (); System.out.println ("Get write Lock:" +System.currenttimemillis ()); Thread.Sleep (1000); } finally{lock.writelock (). Unlock (); }        } Catch(Exception e) {e.printstacktrace (); }    }

Synchronized and lock usage differences:

    1. The synchronized is managed for the JVM to execute. And lock is the code for the Java-written control lock.
    2. The synchronized primitive uses the CPU pessimistic locking mechanism, that is, the thread obtains the exclusive lock. An exclusive lock means that other threads can only rely on blocking to wait for the thread to release the lock. When the CPU conversion thread is blocked, it causes a thread context switch, which results in low efficiency.
    3. Lock uses an optimistic locking method. Each time you do not lock, but assume that there is no conflict to complete an operation, if the conflict failed to retry. Until it succeeds.
    4. Reentrantlock must release the lock in Finally, and synchronized does not need it.
    5. Reentrantlock provides a polling lock request, he can try to get the lock, if successful then continue processing, get unsuccessful, you can wait for the next run time processing, so it is not easy to create a deadlock. Synchronized, however, is more likely to generate deadlocks once they enter the lock request either successfully or continuously blocked.
    6. Synchronized, the lock is scoped to the entire method or synchronized block, and lock is a method call that can span methods and be more flexible.

Use the Reentrantlock scenario:

    1. A thread needs to be interrupted while waiting for control of a lock.
    2. Need to separate some wait-notify,reentrantlock inside the condition application, to control which thread notify.
    3. With the fair lock function, each incoming thread will be queued.

Java Reentranlock 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.