Locks in Java

Source: Internet
Author: User

built-in lock sychronized with volatile;

1.volatile essentially tells the JVM that the value of the current variable in the register (working memory) is indeterminate and needs to be read from main memory; Synchronized is locking the current variable, and other threads are blocked if the variable is accessible to the thread .

2.volatile can only be used at variable levels; synchronized can be used in variables, methods, and class-level

3.volatile can only implement variable visibility and ensure atomicity, while synchronized can guarantee the change of the variable visibility and atomicity

4.volatile does not cause thread blocking, and synchronized can cause thread blocking.

5.volatile tagged variables are not optimized by the compiler; Synchronized tagged variables can be optimized by the compiler

Display lock

Display lock

Prior to JDK5, the available synchronization mechanisms were only synchronized keywords and volative variables, and JDK5 added a new locking mechanism: Reentrantlock, Reentrantlock is not a replacement for built-in locks, It is an optional advanced feature when the built-in lock mechanism is not applicable.

JDK5 provides the lock tool class are under the Java.util.concurrent.locks package, there are condition, lock, Readwritelock and other interfaces:

Lock : The interface supports locking rules that differ in semantics (reentrant, fair, and so on) and can be used in the context of non-blocking structures, including Hand-over-hand and lock rearrangement algorithms. The main implementation is ReentrantLock .

1  Public classcounter{2     PrivateLock lock =NewLock ();3     Private intCount = 0;4 5      Public intInc () {6 Lock.lock ();7         intNewcount = + +count;8 Lock.unlock ();9         returnNewcount;Ten     } One}

The lock () method locks the Lock instance object so that all threads that call the lock () method on the object are blocked until the unlock () method of the lock object is called.

ReadWriteLock : The read-write lock interface defines a lock in a similar manner that some readers can share while the writer is exclusive. This package only provides an implementation, that is ReentrantReadWriteLock , because it applies to most of the standard usage contexts. But programmers can create their own implementations that apply to non-standard requirements.

Condition : An interface describes a condition variable that may be associated with a lock. These variables are similar in usage to implicit monitors that use object.wait access, but provide more powerful functionality. It should be noted that a single Lock may be associated with multiple Condition objects.

In most cases, the display lock works well, but there are limitations, such as the inability to break a thread that is waiting to acquire a lock, or an infinite wait when the request acquires a lock. Lock provides an unconditional, polling, timed, and interruptible lock-fetching operation, all of which are displayed in a lock-and-lock manner. The following code gives the standard form used by the lock interface and must release the lock in finally:

 1  lock lock = new   Reentrantlock ();  2   ...  3  lock.lock (); //  show lock   4  {  5   ...  6 }finally  { //
     show release lock  8    Lock.unlock ();  9 } 

The Boolean Trylock () interface implements a timing and polling acquisition lock, which has a more sophisticated error recovery mechanism than the unconditionally acquired lock, which is a serious problem in the built-in lock, and the only way to recover the program is to restart the application. The way to prevent deadlocks is to avoid inconsistent lock sequences when constructing programs. Timing and polling provide another way to avoid the occurrence of deadlocks. The following code implements a polling acquisition lock, and if two locks cannot be obtained at the same time, then the retry is returned:

1  Public BooleanTransferMoney (account Fromacct, account Toacct) {2      while(true) {  3         if(FromAcct.lock.tryLock ()) {4             Try {  5                 if(ToAcct.lock.tryLock ()) {6                     Try {  7                         ...  8                     }  9                     finally {  Ten ToAcct.lock.unlock ();  One                     }   A                 }   -             }   -             finally {   the FromAcct.lock.unlock ();  -             }   -         }   -     }   +}

Read-write Lock: Controlled by the JVM, guaranteed to read and write mutually exclusive.

The following is a map class wrapped with a read-write lock

1  Packagethread; 2   3 ImportCom.sun.org.apache.bcel.internal.generic.NEW; 4   5 ImportJava.util.Map; 6 ImportJava.util.concurrent.locks.Lock; 7 ImportJava.util.concurrent.locks.ReadWriteLock; 8 ImportJava.util.concurrent.locks.ReentrantReadWriteLock; 9   Ten /**  One * @description A  *   -  * @authorChenzehe - * @email [email protected] the * @create 2013-1-9 pm 09:05:58 -  */   -    -  Public classReadwritemap<k, v> {   +     Private FinalMap<k, v>map;  -     Private FinalReadwritelock lock =NewReentrantreadwritelock ();  +     Private FinalLock r =Lock.readlock ();  A     Private FinalLock W =Lock.writelock ();  at        -      PublicReadwritemap (Map<k, v>map) {   -          This. Map =map;  -     }   -        -      Publicv put (K key, V value) { in W.lock ();  -         Try {   to             returnmap.put (key, value);  +         }   -         finally {   the W.unlock ();  *         }   $     }  Panax Notoginseng        -      PublicV get (Object key) { the R.lock ();  +         Try {   A             returnMap.get (key);  the         }   +         finally {   - R.unlock ();  $         }   $     }   -}

Locks in Java

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.