I. The following is a code snippet of the core data cache mechanism implemented by several experts for your reference. For the core code of this snippet, refer to sun's source code implementation. Sun is not open to this code segment. Its functions have been implemented in ArrayBlockingQueue (jdk1.5) and provide open interfaces. If you do not have time to read the following code, you can directly view the ArrayBlockingQueue api. If you are not interested in the ArrayBlockingQueue object, you can directly call ConcurrentHashMap (jdk1.5), ConcurrentSkipListMap (jdk1.6, the api has a more detailed description. Here we will not mention it. Note that this function solves the problem of multi-thread concurrency. Therefore, null cannot be used as the key value of the key and value, which can be understood as the improvement of HashTable.
The code is as follows: |
Copy code |
Package com. henry; Import java. util. HashMap; Import java. util. Map; Import java. util. Random; Import java. util. concurrent. locks. ReadWriteLock; Import java. util. concurrent. locks. ReentrantReadWriteLock; Public class CacheDataTest { Static Map <Integer, Object> dataMap = new HashMap <Integer, Object> (); Static ReadWriteLock lock = new ReentrantReadWriteLock (); // Create a read/write lock instance Static Object getData (Integer key ){ Lock. readLock (). lock (); // lock before reading Object val = null; Try { Val = dataMap. get (key ); If (val = null ){ // Must release read lock before acquiring write lock Lock. readLock (). unlock (); Lock. writeLock (). lock (); Try {if (val = null ){ // DataMap. put (key, ""); // query from db Val = queryDataFromDB (key);} finally { // Downgrade by acquiring read lock before releasing write lock Lock. readLock (). lock (); // Unlock write, still hold read Lock. writeLock (). unlock ();} } Finally { Lock. readLock (). unlock (); // do not forget to release the lock System. out. println ("get data key =" + key + "> val =" + val ); Return val; Static Object queryDataFromDB (Integer key ){ Object val = new Random (). nextInt (1000 ); DataMap. put (key, val ); System. out. println ("write into data key =" + key + "> val =" + val ); Return val; } Public static void main (String [] args ){ For (int I = 0; I <10; I ++ ){ New Thread (new Runnable () {public void run (){ GetData (new Random (). nextInt (5 )); }). Start ();} } |