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;
}
});
}
}