See Concurrenthashmap source code when see lock this lock mechanism, do not understand it and synchronized difference, check some data record down, in Lock's document, the explanation of lock is: lock implementation than synchronized Provides additional lock operations with a more flexible structure that can support different properties and can support multiple related conditions of an object. Let's take a look at what lock can provide for additional operations than synchronized, which is to solve the synchronized problem:
1. It cannot interrupt a thread that is waiting to acquire a lock
2, also can't vote to get lock, if do not want to wait, also can't get lock.
The first problem can be done using the lockinterruptibly () method, and the lockinterruptibly () method is executed as follows:
If the lock is not persisted by another thread, gets the lock and returns immediately, setting the locked hold count to 1.
If the current thread is already holding this lock, the count will be added to 1, and the method returns immediately.
If the lock is persisted by another thread, the current thread is disabled for thread scheduling purposes, and the thread will remain dormant until one of the following two situations occurs:
A, the lock is obtained by the current thread;
b, or one of the other threads interrupts the current thread.
If the current thread obtains the lock, the lock hold Count is set to 1.
If the current thread:
A, the interrupt state of the thread has been set when entering this method;
b, or is interrupted while waiting for the lock to be acquired.
Interruptedexception is thrown, and the current thread's interrupted state is cleared.
That is, the lockinterruptibly () method allows the other thread to call its Thread.Interrupt method when it waits for it to be returned directly, without acquiring the lock and throwing a interruptedexception.
The second problem uses the Trylock () method or Trylock (long timeout, Timeunit timeunit) method. Trylock () Method: If a lock is acquired immediately returns true, if another line is impersonating holds the lock, returns false immediately;
Trylock (long timeout, Timeunit timeunit) method: If the lock is acquired immediately returns true, if another line is impersonating holds the lock, it waits for the parameter given the time, in the process of waiting, if the lock is acquired, returns true if the wait time-out, return false; see an example: hit a not very appropriate score: You are busy working now, suddenly feel bursting, so you run to the bathroom, to the door to find a "clean, suspended" card. No way, work and busy, so you have to give up to the bathroom back to work, may be so repeated, finally you found that you can enter, so ...
How do you make a scene like this with synchronized? No way, if synchronized, when you find the bathroom can not temporarily inaccessible, you can only wait at the door. and using Trylock (), first you try to go to the bathroom, found temporarily unable to enter (Trylock return false), so you continue to busy your work, so repeatedly, until you can enter the toilet (Trylock return true). Even if you are in a hurry, you can try sex at the door for 20 seconds, no more busy work (Trylock, timeunit.seconds);).
Synchrozized:
When the code block is added synchrozized, there are two changes. One is atomicity (atomicity) and one is visibility (visibility). Atomicity means that only one thread at a time can get a code lock and go into a block of code surrounded by synchronized. The visibility is the consistency of the variable changes in different scopes. The emphasis on variable visibility and consistency is due to the fact that in Java memory, memory caches and compiler optimizations can cause a variety of anomalous behavior under multithreaded conditions. In general, threads are not constrained by the values of cached variables in a way that does not have to be immediately visible to other threads (regardless of whether they are in registers, processor-specific caches (CPU caches), or through instruction Reflow or other compiler optimizations). However, after the Synchronized keyword is added, the runtime will ensure that updates made by a thread to the variable precede the update to the existing synchronized block, and when entering another synchronized block protected by the same monitor (lock), Updates to these variables are immediately visible. Similar rules exist in volatile variables.
Lock:
Since JDK1.5 thought, Java provided java.util.concurrent this and the contract, in its sub-package locks, provides a series of abstract classes about locks. There are two kinds of locks: reentrantlock,reentrantreadwritelock. The implementation of the Reentrantlock lock example is as follows:
Lock lock = new Reentrantlock (); try { lock.lcok (); Do something} finally { lock.unlock ();}
above this code, first create a lock, then call its lock () method, open the lock, at the last call its unlock () unlocked. It should be noted that when using a lock, you should write the code in the style above, that is, Lock.unlock () is best placed in the finally block, which prevents the exception from executing do something, causing the lock to never be released.
Reentrantreadwritelock usage is basically the same as Reentrantlock, except that Reentrantreadwritelock implements special rules (read-write locks), In Reentrantreadwritelock there are two inner classes Reentrantreadwritelock.readlock and Reentrantreadwritelock.writelock (actually more than two inner classes, There is the Abstractqueuedsynchronizer sync, etc.), these two classes can be returned using Reentrantreadwritelock's Readlock () and Writelock (), respectively. The rule for this read-write lock is that, as long as there is no writer, the read lock can be persisted by multiple reader threads while the write lock is exclusive. Examples of reentrantreadwritelock Locks:
Package Test.mult;import java.util.concurrent.locks.reentrantreadwritelock;/*** @ClassName: readwritelocktest* @ Author Whwang* @date 2012-1-11 pm 02:20:59 */public class Readwritelocktest {static Reentrantreadwritelock lock = new R Eentrantreadwritelock (TRUE); public static void Main (string[] args) {//can enter multiple reader-can//can enter more than one writer-not//when reader enters , writer can enter-can not//when there is writer entered, reader can enter-can not MyThread t1 = new MyThread (0, "T1"); MyThread t2 = new MyThread (0, "T2"); MyThread t3 = new MyThread (1, "T3"); T1.start (); T2.start (); T3.start (); } private static Class MyThread extends Thread {private int type; Private String ThreadName; public MyThread (int type, String threadname) {this.threadname = ThreadName; This.type = type; @Override public void Run () {while (true) {if (type = = 0) { Read Reentrantreadwritelock.readlock readlock = null; try {readlock = Lock.readlock (); Readlock.lock (); System.err.println ("to read ...." + ThreadName); try {thread.sleep (5 * 1000); } catch (Interruptedexception e) {e.printstacktrace (); }} finally {Readlock.unlock (); }} else {//write reentrantreadwritelock.writelock Writelock = null ; try {writelock = Lock.writelock (); Writelock.lock (); System.err.println ("to write ...." + ThreadName); try {thread.sleep (5 * 1000); } catch (Interruptedexception e) {E.printstacktrace (); }} finally {Writelock.unlock (); } } } } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The difference between synchronized and Java.util.concurrent.locks.Lock