HOW TO CACHE RESULTS TO BOOST PERFORMANCE

本文介绍了一种通过缓存计算结果来提升程序性能的方法,并对比了简单缓存与线程安全缓存实现的区别。通过示例代码展示了如何使用HashMap实现基本缓存逻辑,以及如何借助ConcurrentHashMap和FutureTask构建线程安全且避免重复计算的缓存机制。
摘要由CSDN通过智能技术生成

http://www.javacreed.com/how-to-cache-results-to-boost-performance/

最简单的想法
IF value in cached THEN
return value from cache
ELSE
compute value
save value in cache
return value
END IF

例如:
package com.javacreed.examples.cache.part1;

import java.util.HashMap;
import java.util.Map;

public class NaiveCacheExample {

private Map<Long, Long> cache = new HashMap<>();

public NaiveCacheExample() {
// The base case for the Fibonacci Sequence
cache.put(0L, 1L);
cache.put(1L, 1L);
}

public Long getNumber(long index) {
// Check if value is in cache
if (cache.containsKey(index)) {
return cache.get(index);
}

// Compute value and save it in cache
long value = getNumber(index - 1) + getNumber(index - 2);
cache.put(index, value);
return value;

}
}

三个问题:
1、线程不安全
2、有可能重复计算
3、hard code

推荐的方式:

public class GenericCacheExample<K, V> {

//ConcurrentHahsMap线程安全
private final ConcurrentMap<K, Future> cache = new ConcurrentHashMap<>();

private Future createFutureIfAbsent(final K key, final Callable callable) {
Future future = cache.get(key);
if (future == null) {
final FutureTask futureTask = new FutureTask(callable);
//putIfAbsent
future = cache.putIfAbsent(key, futureTask);
if (future == null) {
future = futureTask;
futureTask.run();
}
}
return future;
}

//算法是callable传进来的
public V getValue(final K key, final Callable callable) throws InterruptedException, ExecutionException {
try {
final Future future = createFutureIfAbsent(key, callable);
return future.get();
} catch (final InterruptedException e) {
cache.remove(key);
throw e;
} catch (final ExecutionException e) {
cache.remove(key);
throw e;
} catch (final RuntimeException e) {
cache.remove(key);
throw e;
}
}

public void setValueIfAbsent(final K key, final V value) {
createFutureIfAbsent(key, new Callable() {
@Override
public V call() throws Exception {
return value;
}
});
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值