"java Concurrency series 04" thread lock synchronized and lock and volatile and condition

Source: Internet
Author: User

first, Preface

How multithreading prevents competing resources, that is, to prevent concurrent operations on the same resource, is to use the lock Mechanism. This is a point of knowledge that must be understood in Java concurrency programming. In fact, it is relatively simple to use, but it must be understood.

There are several concepts that must be kept in mind:

    • Lock must be Locked.
    • You must release the lock after you have finished executing
    • Same time, same lock, only one thread can execute
second, synchronized

Synchronized is characterized by the automatic release of the lock, the role of the method automatically acquire the lock , any object can be used as a lock, it is the most common locking mechanism, locking a few lines of code, as Follows:

// --------synchronization Method 1  public synchronized void test () {    // piece of code }//--------synchronization Method 2Private Object lock=New  object ();  public void test2 () {    synchronized(lock) {            }}
2.1 Synchronized acquired lock

Synchronized can manually specify a lock, which is automatically acquired when acting on a method:

    • Works on the normal method to obtain the current object lock, equivalent to synchronized (this)
    • A static method is used to obtain a class lock, equivalent to synchronized (class. Class)
third, Lock

Lock is characterized by the need to create the lock yourself (the lock type is already specified as the implementation class for lock, you cannot use other objects), and you must release the lock YOURSELF. The code structure is as Follows:

Lock L = ...; l.lock (); Try {    //  execute code finally  {    l.unlock ();}

Note that you must release the lock in finally to ensure that even if an exception is thrown, it can be released.

3.1 Reentrantlock Detailed

This is an example of a lock.

3.1.1 Construction method

Reentrantlock (can be re-entered lock), only one property is Fair. Fairness means that when there are multiple threads competing for a lock, the first served gets the lock, but when using a fair strategy, it has a certain effect on efficiency.

    • Reentrantlock (): most commonly used to get an unfair lock,
    • Reentrantlock (boolean fair): Gets the lock for the specified fair policy.
3.1.2 Method Summary

Locking and Unlocking:

    • void lock (): Gets the lock, which is the most common method.
    • void unlock (): Release the lock, the method must be used, you must release the LOCK.
    • Boolean Trylock (): the lock is acquired only if the lock is not persisted by another thread at the time of the Call. Would undermine the principle of fairness.
    • Boolean trylock (long timeout, timeunit unit): Gets the lock if it has not been persisted by another thread within a given wait time and the current thread has not been interrupted.
    • void lockinterruptibly (): Gets the lock if the current thread is not Interrupted.

Query the relevant status of the current Lock:

    • Boolean isLocked (): queries whether this lock is persisted by any thread.
    • Boolean Isheldbycurrentthread (): queries whether the current thread holds this LOCK.
    • Boolean Isfair (): returns True if the fairness of this lock is set to True.
    • int getholdcount (): Query the number of times the current thread has held this LOCK.
    • int Getqueuelength (): Returns the estimated number of threads that are waiting to get this lock.
    • Boolean Hasqueuedthread (thread thread): queries whether a given thread is waiting to acquire this lock.
    • Boolean hasqueuedthreads (): query whether some threads are waiting to acquire this lock.

Condition related (see Chapter fifth):

    • Condition newcondition (): Returns the Condition instance used with this Lock instance.
    • int Getwaitqueuelength (Condition Condition): Returns the number of thread estimates waiting for the given condition associated with this LOCK.
Iv. Readwritelock

When there is a situation where there are multiple methods in a class that need to be synchronized, which have read and write, and if all methods use synchronization, while guaranteeing the accuracy of the data, synchronization can have a greater impact on performance when the number of reads is much larger than the number of Writes. At this time, there is a synchronization policy, read and read operations are not mutually exclusive, read and write operations mutually exclusive, write operations and write operations mutually exclusive, so as to provide performance.

Although the explanation is very popular, it is important to consider the following scenarios (all from the JDK api):

    1. When writer releases a write lock, both reader and writer are in a wait state, at which point to determine whether to grant a read lock or a write lock. Writer has precedence over common, because the expected time to write is shorter and less frequent. Reader priority is less common, because if reader is as frequent and persistent as expected, it will result in longer latencies for write Operations. It is also possible to achieve fairness or "in order".
    2. Determines whether read locks are granted to reader requesting read locks when reader is active while writer is in a wait State. Reader Precedence delays writer for an indefinite period, while writer takes precedence to reduce possible concurrency.
    3. Determine if you want to re-enter the lock: can I retrieve it using a thread with a write lock? Can I get a read lock while holding the write lock? Can I re-enter the write lock itself?
    4. Can I downgrade a write lock to a read lock without allowing other writer interference? Can read locks be promoted to write locks in favor of other waiting reader or writer?
4.1 Creating and acquiring locks

Create Reentrantreadwritelock:

    • Reentrantreadwritelock (): creates a default, non-fair lock.
    • Reentrantreadwritelock (boolean fair): Creates a lock that specifies a fair policy.

Get read or write Lock:

    • Readlock (): Returns the lock used for the read Operation.
    • Writelock (): Returns the lock used for the write Operation.
4.2 Other methods

Other methods are less common, and you can view the API documentation if you have specific needs.

4.3 example

Here is a simple example of a concurrent access map:

classRwdictionary {Private Finalmap<string, data> m =Newtreemap<string, data>(); Private FinalReentrantreadwritelock RWL =NewReentrantreadwritelock (); Private FinalLock r =Rwl.readlock (); Private FinalLock W =Rwl.writelock ();  publicData get (String key) {r.lock (); Try{returnM.get (key);} finally{r.unlock ();} }     publicstring[] AllKeys () {r.lock (); Try{returnm.keyset (). ToArray ();} finally{r.unlock ();} }     publicdata put (String key, data value) {w.lock (); Try{returnm.put (key, value);} finally{w.unlock ();} }     public voidClear () {w.lock (); Try{m.clear ();} finally{w.unlock ();} } }

But it is still not recommended, because there are already concurrenthashmap.

4.4 Reentrantreadwritelock Understand if the 4.4.1 lock sequence can be specified as a read or write lock

no, either randomly or in accordance with the fairness policy, prioritize the thread that waits the longest to get the lock it wants.

4.4.2 What is lock re-entry

Allows reader and writer to regain read or write locks in accordance with the Reentrantlock Style. After all write locks held by the write thread have been freed, the re-entry reader is allowed to use Them.

In addition, writer can obtain a read lock, but the reverse is not True. In other applications, a re-entry is useful when a write lock is persisted during a call or callback to a method that performs a read operation in a read-lock State. If reader attempts to acquire a write lock, it will never succeed.

4.4.3 What is lock demotion

The re-entry also allows the downgrade from a write lock to a read lock, which is achieved by acquiring a write lock, then acquiring a read lock, and finally releasing the write Lock. however, It is not possible to upgrade from a read lock to a write lock.

V. Volatile

I think this keyword water is deep, easy not to use it in sync, volatile Chinese meaning is not stable. Look for an example of the JDK source code (jdk1.8 about 130 classes using volatile), the thread class Has:

Private volatile Interruptible blocker;

This is the Thread's interrupt-related variable, and throws an exception as soon as a thread gets the interrupt it needs. Here is a variable inside the hashmap:

transient volatile int modcount;

The variable is a counter that is used to throw an exception when the iteration changes to the Container.

5.1 Small Summary

When to use Volatile: when a variable needs to be a signal, with various states, changing state will trigger an operation, use Volatile.

A simple explanation is that when a thread reads a variable, it caches the variable, so if you are sensitive to a change in a signal that requires volatile, you cannot use the cache, and you need to read the actual value each Time. finally, It makes no sense to attempt to i++ the volatile variable concurrently.

liu, Condition

This is the addition of the class added by the lock class, after all, the Object's wait and notify method in the Synchronized statement block, since now with lock of course to add a new waiting to wake up mechanism, the JDK API has been made Clear:

The example is enough to illustrate the usage, so the Java API documentation is the best reference:

classBoundedbuffer {FinalLock lock =NewReentrantlock (); FinalCondition Notfull =lock.newcondition (); FinalCondition Notempty =lock.newcondition (); Finalobject[] items =Newobject[100]; intputptr, takeptr, count;  public voidPut (Object X)throwsinterruptedexception {lock.lock (); Try {        while(count = =Items.length) notfull.await (); items[putptr]=x; if(++putptr = = Items.length) Putptr = 0; ++count;     Notempty.signal (); } finally{lock.unlock (); }   }    publicObject Take ()throwsinterruptedexception {lock.lock (); Try {        while(count = = 0) notempty.await (); Object x=items[takeptr]; if(++takeptr = = Items.length) Takeptr = 0; --count;       Notfull.signal (); returnx; } finally{lock.unlock (); }   }  }

This is the most basic usage.

6.1 Construction methods

There is no specific construction method to obtain the Condition object through the lock implementation object, and lock has the following method: newcondition (): returns the Condition instance used with this lock instance.

6.2 Common methods

The condition method and object are similar to the waiting wake:

    • Void await (): causes the current thread to wait until it receives a signal or is Interrupted.
    • Boolean await (long time, timeunit unit): causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified wait Time.
    • Long Awaitnanos (long nanostimeout): causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified wait Time.
    • void awaituninterruptibly (): causes the current thread to remain in a wait state until it receives a signal.
    • Boolean Awaituntil (Date deadline): causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified deadline.
    • void signal (): wakes up a waiting thread.
    • void Signalall (): wakes all waiting threads.

The wait becomes the await method, and the awakening becomes the signal method.

"java Concurrency series 04" thread lock synchronized and lock and volatile and condition

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.