Thread locks are like synchronized techniques in a traditional threading model, but are more object-oriented than sychronized, and the lock itself should be an object, similar to a lock in life. Code snippets executed by two threads if you want to achieve the effect of a synchronous mutex, they must use the same lock object. A lock is an internal method on the class that represents the resource to be manipulated, not in the thread code. This blog post mainly summarizes the use of lock lock and Readwritelock lock in thread lock technology.
With the foundation of synchronized, lock is relatively simple, first look at an example:
Public class locktest { Public Static void Main(string[] args) {NewLocktest (). Init (); }Private void Init() {FinalOutputer Outputer =NewOutputer ();//thread 1 print: Duoxiancheng NewThread (NewRunnable () {@Override Public void Run() { while(true) {Try{Thread.Sleep (5); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } outputer.output ("Duoxiancheng"); }}). Start (); ;//Thread 2 print: Eson15 NewThread (NewRunnable () {@Override Public void Run() { while(true) {Try{Thread.Sleep (5); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } outputer.output ("Eson15"); }}). Start (); ; }//Customize a class to save locks and pending tasks StaticClass Outputer {Lock lock =NewReentrantlock ();//Define a lock, lock is an interface, you need to instantiate a specific lock //String printing method, character printing Public void Output(String name) {intLen = Name.length (); Lock.lock ();Try{ for(inti =0; i < Len; i++) {System.out.print (Name.charat (i)); } System.out.println (""); }finally{Lock.unlock ();The reason//try up is that if a thread goes in and hangs up or throws an exception, the lock is not released at all .} }}
This example is similar to the previous example of synchronized, except that the synchronized is changed to lock. As can be seen from the program, the use of lock, you need to first a lock object, and then the thread task need to synchronize the place locked, but must remember to put the lock, so use try block to deal with a bit, will put the lock action in the finally block.
This is the case of a thread task, if the two thread task is not troublesome, or a new task method in this class, because lock is a member of this class variable, or can use this lock, and must use this lock, because to achieve synchronous mutex, you must use the same lock.
| 2. The magic of reading and writing locks |
Lock is divided into read and write lock, read lock and read lock is not mutually exclusive, read lock and write lock mutex, write lock and write lock mutex, which is controlled by the JVM itself. This is very well understood, read, everyone can read, no changes to the data, as long as it involves writing, it may be problematic. We write the code as long as the corresponding lock in the correct position. The read-write lock has an interface called Readwritelock, we can create a specific read-write lock instance, through the read-write lock can also get read lock and write lock. Here is an example of a read-write lock:
2.1 Basic usage of read-write locks
Public class readwritelocktest { Public Static void Main(string[] args) {FinalQueue3 q3 =NewQueue3 ();//Encapsulates shared data, read-write locks, and classes for tasks to be performed for(inti =0; I <3; i++) {NewThread () {//Open three threads to write data Public void Run() { while(true) {Q3.put (NewRandom (). Nextint (10000)); }}}.start ();NewThread () {//Open three threads read Data Public void Run() { while(true) {q3.get (); }}}.start (); }}}class Queue3 {PrivateObject data =NULL;//Shared data PrivateReadwritelock RWL =NewReentrantreadwritelock ();//define read/write locks //Task method for reading data Public void Get() {Rwl.readlock (). Lock ();//read-on lock Try{System.out.println (Thread.CurrentThread (). GetName () +": Before read:"+ data);//Print data display before readingThread.Sleep ((Long) (Math.random () * +));//sleep for a while ~System.out.println (Thread.CurrentThread (). GetName () +": After read:"+ data);//Print data display after reading}Catch(Interruptedexception e) {E.printstacktrace (); }finally{Rwl.readlock (). Unlock ();//Release read lock} }//Task method for writing data Public void put(Object data) {Rwl.writelock (). Lock ();//Upper write lock Try{System.out.println (Thread.CurrentThread (). GetName () +": Before write:"+ This. data);//Print data display before readingThread.Sleep ((Long) (Math.random () * +));//sleep for a while ~ This. data = data;//Write DataSystem.out.println (Thread.CurrentThread (). GetName () +": After write:"+ This. data);//Print data display after reading}Catch(Interruptedexception e) {E.printstacktrace (); }finally{Rwl.writelock (). Unlock ();//Release write lock} }}
In order to illustrate the characteristics of read and write locks (read lock and read lock are not mutually exclusive, read lock and write lock mutex, write lock and write lock mutex), I first put the above two task methods locked and release lock four lines of code commented out, to see the results of the operation:
In fact, whether it is to comment out the lock or comment off the lock or full comment out, there will be problems, write the time will be wired to read. Then add the read-write lock, and then look at the results of the operation:
As can be seen, with read and write locks, the various threads run orderly, from the results, also confirms that the read lock and read lock is not mutually exclusive, write lock and read lock, write lock are mutually exclusive features.
2.2 Read and write locks are used to cache data
Now use a read-write lock to write a slightly higher-level app demo, which simulates caching data. The functions implemented are as follows: Now there are 5 threads that need data, there is no data at first, so the thread that first went to fetch the data found no data, it had to initialize a data, and then the other threads can take the data directly. The code is as follows:
Public class ReadWriteLockTest2 { Public Static void Main(string[] args) {CacheData cache =NewCacheData (); for(inti =1; I <=5; i + +) {//Open 5 threads NewThread (NewRunnable () {@Override Public void Run() {Cache.processcache ();//Go get the data.}}). Start (); }}}class CacheData {PrivateObject data =NULL;//data that needs to be cached Private BooleanCachevalid;//To mark whether there is cached data PrivateReadwritelock RWL =NewReentrantreadwritelock ();//define read/write locks Public void Processcache() {Rwl.readlock (). Lock ();//read-on lock if(!cachevalid) {//If there is no cache, the description is the first access, need to assign a value to dataRwl.readlock (). Unlock ();//Release the read lock firstRwl.writelock (). Lock ();//Upper write lock if(!cachevalid) {System.out.println (Thread.CurrentThread (). GetName () +": No cache!"); data =NewRandom (). Nextint ( +);//Assigned valueCachevalid =true;//The tag is already cachedSystem.out.println (Thread.CurrentThread (). GetName () +": Already cached!"); } rwl.readlock (). Lock ();//Read on the lock againRwl.writelock (). Unlock ();//To release the write lock just above} System.out.println (Thread.CurrentThread (). GetName () +"Get Data:"+ data); Rwl.readlock (). Unlock ();//Release read lock}}
As can be seen from the code, the alternate use of Read and write locks in the Processcache method. At first, they read the data, so at first it was read-lock, but when the first thread came in and found no cache data, it had to write the data, then it had to release the read lock, change the write lock, tell other threads: "Hey, dude, there's no data at all, we've been pits, Let me get a data first, I'm sorry you have to wait ~ ", wait until the thread initializes the data, the other threads can read it, then it locks up the read lock, releases the write lock, and then it goes out. This simulates a demo of the cached data, which can be seen in a method where the same thread can manipulate two locks. Look at the results of the operation:
Thread-1: No cache!
Thread-1: Already cached!
Thread-1 Get data:893
Thread-0 Get data:893
Thread-2 Get data:893
This and hibernate in the load (ID, Class.class) method is a bit similar, first get the proxy object, to use the object, if found not, the new generation, if there is a direct use.
2.3 Read-write lock for cache system
Continue to advance, if you want to cache multiple data now, that is, to write a cache system, then how to do? A cache system is nothing more than a container, can store a lot of cached data, it is natural to think of using a map, specifically loaded cache data, and then for multiple threads to use. So the whole idea of the design, with the above to cache a single data is the same, but just think of something more, look at the code:
Public class cachedemo { Public Static void Main(string[] args) {Cache CAC =NewCache (); for(inti =0; I <3; i + +) {//Open three threads to go to cache and take key cache1 data, NewThread (NewRunnable () {@Override Public void Run() {String value = (string) cac.getdata ("Cache1");//The first thread to enter is to write a data in (equivalent to the first time taken from the database)System.out.println (Thread.CurrentThread (). GetName () +": "+ value); }}). Start (); } for(inti =0; I <3; i + +) {//Open three threads to cache data with key Cacahe2 NewThread (NewRunnable () {@Override Public void Run() {String value = (string) cac.getdata ("Cache2");//The first thread to enter is to write a data in (equivalent to the first time taken from the database)System.out.println (Thread.CurrentThread (). GetName () +": "+ value); }}). Start (); }}}class Cache {//Map to store cached data, note that HashMap is non-thread-safe and also synchronized Privatemap<string, object> cache = Collections.synchronizedmap (NewHashmap<string, object> ());PrivateReadwritelock RWL =NewReentrantreadwritelock ();//define read/write locks Public synchronizedObjectGetData(String key) {Rwl.readlock (). Lock ();//read-on lockObject value =NULL;Try{value = Cache.get (key);//The data is taken from the cache according to key if(Value = =NULL) {//If the key corresponds to the data for the first time, you cannot getRwl.readlock (). Unlock ();//Release read lockRwl.writelock (). Lock ();//Replace with write lock Try{if(Value = =NULL) {//The reason to judge, is to prevent a few threads at the same time to enter the above if, and then each to rewrite the assignment againSystem.out.println (Thread.CurrentThread (). GetName () +"Write Cache for"+ key); Value ="AAA"+ System.currenttimemillis ();//actual is to go to the database to fetch, here is just the simulationCache.put (key, value);//Put in the cacheSystem.out.println (Thread.CurrentThread (). GetName () +"has already written cache!"); } }finally{Rwl.writelock (). Unlock ();//write up release write lock} rwl.readlock (). Lock ();//change-read lock} }finally{Rwl.readlock (). Unlock ();//Finally release read lock}returnValue//Return the data to be taken}}
The structure of the entire code is the same as above, and it is not difficult to understand the code once the individual data is cached. Here is just a demo, the actual can be dealing with the database, the first time from the cache is definitely not, then go to the database to check, and then put the data taken into the cache, the next time other threads can be directly from the cache to take. Look at the results of the operation:
Thread-0 Write Cache for Cache1
Thread-0 has already written cache!
Thread-4 Write Cache for Cache2
Thread-0: aaa1464782404722
Thread-4 has already written cache!
Thread-4: aaa1464782404723
Thread-3: aaa1464782404723
Thread-2: aaa1464782404722
Thread-1: aaa1464782404722
Thread-5: aaa1464782404723
From the results can be seen, thread 0 first go to cache to take key to Cache1 value, did not get, wrote to the inside of a, and then thread 4 to the cache to take key to Cache2 value also did not get, so also wrote a, in this period thread 0 value took out, after a few threads also later took out.
The application of read-write locks is still very extensive and very useful. So much for the technology of the thread lock.
Related reading: http://blog.csdn.net/column/details/bingfa.html
-Willing to share and progress together!
-More articles please see: http://blog.csdn.net/eson_15
The use of "Java Concurrency" thread lock technology