/**
* 并发性太差,主要体现在计算不同值,计算相同值效率高
*/
@Test
public synchronized void cache1() {
Map<String, String> cache = new HashMap<>();
String result = cache.get(arg);
if (result == null) {
result = compute(arg);
cache.put(arg, result);
System.out.println(result);
}
}
/**
* 计算相同值时存在重复计算,不同值时效率高
*/
@Test
public void cache2() {
Map<String, String> cache = new ConcurrentHashMap<>();
String result = cache.get(arg);
if (result == null) {
result = compute(arg);
cache.put(arg, result);
System.out.println(result);
}
}
//对于同一个值,因为get的value是futureTask,所以速度快很多,出现重复计算同一个值
//的几率小很多
@Test
public void cache3() throws Exception {
Map<String, FutureTask<String>> cache = new ConcurrentHashMap<>();
if (cache.get(arg) == null) {
FutureTask<String> futureTask = new FutureTask<>(() -> compute(arg));
cache.put(arg, futureTask);
String result = futureTask.get();
System.out.println("result = " + result);
} else {
System.out.println(cache.get(arg).get());
}
}
/**
* 相同值时,利用原子的putIfAbsent判断是否有值,避免了重复计算
* @throws Exception
*/
@Test
public void cache4() throws Exception{
Map<String, FutureTask<String>> cache = new ConcurrentHashMap<>();
if(cache.get(arg)==null){
FutureTask<String> futureTask = new FutureTask<>(() -> compute(arg));
FutureTask<String> f = cache.putIfAbsent(arg, futureTask);
if(f==null){
String result = futureTask.get();
System.out.println("result = " + result);
}else{
cache.get(arg).get();
}
}else{
cache.get(arg).get();
}
}
缓存,futureTask,并发
最新推荐文章于 2024-06-01 18:24:42 发布