Java simulates a cache pool through read-write locks

Source: Internet
Author: User

    • Cache pool in the project development time to use, in a look at the relevant information, found that many blogs on the implementation of the cache pool there are some loopholes, today took a little time to comb, An example of getting data from a cache is implemented with the Reentrantreadwritelock in JDK1.5. I have limited skills, if the reader found the bug, please point out. Programmers do not like to say more, directly on the code
    • Code
1 ImportJava.util.HashMap;2 ImportJava.util.Map;3 ImportJava.util.concurrent.locks.ReadWriteLock;4 ImportJava.util.concurrent.locks.ReentrantReadWriteLock;5 6 /**7  * @authorYuguojin8  */9  Public classThreadcache {Ten  One     Private Staticmap<string, object> cachemap =NewHashmap<string, object>(); A  -     Private StaticReadwritelock lock =NewReentrantreadwritelock (); -  the      Public Static voidMain (string[] args) { -  -          for(inti = 0; I < 100; i++) { -             NewThread (NewRunnable () { +  - @Override +                  Public voidrun () { AString obj = (string) get ("TestKey"); at System.out.println (obj); -  -                 } - }). Start (); -  -         } in  -     } to  +      Public StaticObject get (String key) { -Lock.readlock (). Lock ();//Read the lock first theObject value =NULL; *         Try { $Value =Cachemap.get (key);Panax Notoginseng             if(Value = =NULL) {//if the cache does not exist -  the                 //let the thread sleep for 1 seconds for easy testing +                 Try { AThread.Sleep (1000); the}Catch(interruptedexception e) { + e.printstacktrace (); -                 } $   $Lock.readlock (). Unlock ();//if value is null, the read lock is freed, the thread acquires a write lock, and the other thread waits for the write lock to be released before the read lock -Lock.writelock (). Lock ();//Add write Lock -  theValue =Cachemap.get (key); -                 Try {Wuyi                     if(Value = =NULL) { theValue = "Cache Data";//querying the database, retrieving data from the DB -                         //in Cache Wu cachemap.put (key, value); -                     } About}finally { $ Lock.readlock (). Lock (); - lock.writelock (). Unlock (); -                 } -             } A  +}finally { theLock.readlock (). Unlock ();//releases the read lock acquired for the first time -         } $  the         returnvalue; the     } the}
    • Code comments

1. In the code I used a HASHMAP simulation cache, when obtaining data in the CACHEMAP cache if there is no cachemap in the existence of the time it is worth to synchronize data from the database to Cachemap, so that the CACHEMAP is related to read and write operations;

2. When multiple threads acquire the same data at the same time, the problem of thread safety and thread synchronization is involved;

    • Issues that are prone to problems in your code

1. Lock in line 13 must be an attribute-level variable, and it is easy for a novice programmer to write lock as a method variable (this will not work for lock)

2. The code 49 line needs to read the cache data does not exist, and has been given a read lock when it is necessary to verify that the data exists in the cache (to resolve high concurrency when multiple threads concurrently net read lock is, after the result of multiple database query operations)

3. The lock is a resource-intensive operation, and finally the lock must be released, so the finally module is used to release the lock

4. The order of release and acquisition of locks in code 46/47 and code 57/58 cannot be changed (because) in the Java lock mechanism the read lock can be promoted to a write lock, however the write lock is not degraded to read lock, so the read lock must be released before the write lock is acquired, otherwise it will be locked

Java simulates a cache pool through read-write locks

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.