http://blog.csdn.net/michaelwubo/article/details/50865185
Java high concurrency cache with Guava caches
This article is called "Java high concurrency cache and guava cache", but the core is how to effectively prevent the local cache breakdown
Business model:
res = Cache.get (key);
if (res = = null) {
value = SQL;
Cach.put (key, value);
return value;
}
return res;
This code does not work in multithreading:
In multi-threading, when there is no cache in the cache, the same execution of the business data will be executed as many times and return the processed data, we analyze this situation:
(1) When the thread T1 accesses Cachemap, the business data is processed according to the business to the background, and the processing data is returned and put into the cache.
(2) When the thread T2 accesses the Cachemap, it also handles the business data and returns processing data and puts it into the cache based on the business to the background.
The first thing to think about is synchronous synchronized:
res = Cache.get (key);
if (res = = null) {
synchronized (this) {
OldValue = Cache.get (key);
if (OldValue = = null) {
value = SQL;
Cach.put (key, value);
return value;
} else
return oldValue;
}
}
return res;
You can then think of this code as damaging to performance and not for a clustered environment. The cache fails for an instant and all concurrent threads are blocked
And here's the point: Update the cache asynchronously with the future and Concurrentmap
res = Cache.get (key);
if (res = = null) {
futuretask<v> futuretask=new futuretask<v> (callable);
Futurevalue=cachemap.putifabsent (KeyValue, futuretask);
if (futurevalue==null) {
futurevalue=futuretask;
Futuretask.run ();
}
return Futurevalue.get ();
}
return res;
Assuming that the cache is invalidated, concurrent threads are 5, Futuretask is created, putifabsent: If Key-value already exists (when the method is called), that value is returned. If the mapping of the key is not found in the map when it is called, a null value is returned
Therefore, only one thread in the final 5 can get a real execution-blocking-return process, and the other 4 threads may have two situations:
(1) Block-back
(2) Direct return
It's much better than exclusively blocking with SYN sync blocks.