HOW TO CACHE RESULTS TO BOOST PERFORMANCE

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

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章