Java併發編程實戰中提到的一個簡單的緩存系統

這是Java併發編程中提到的一個簡單的緩存系統,不是本人代碼哦,我尚未這麼高的水平。。:) java

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;


interface Computable<K,V>{
	V compute(final K arg);
}

/**
 * 實現簡單緩存系統
 * @author mzy
 *
 * @param <K> key
 * @param <V> value
 */
public class FutureCache<K,V> implements Computable<K,V>{
	private final ConcurrentHashMap<K, Future<V>> cache = new ConcurrentHashMap<K ,Future<V>>();
	private final Computable<K, V> c;
	public FutureCache(Computable<K, V> c) {
		this.c = c;
	}
	
	@Override
	public V compute(final K key) {
		while(true){
			Future<V> future = cache.get(key);
			if(future == null){
				Callable<V> eval = new Callable<V>() {
					@Override
					public V call() throws Exception { return c.compute(key); }
				};
				FutureTask<V> ftask = new FutureTask<V>(eval);
				//使用putIfAbsent原子操做避免有上面if(future == null)引發的相同值的缺陷
				future = cache.putIfAbsent(key, ftask);
				if(future == null) { future = ftask; ftask.run(); }
			}
			try {
				return future.get();
			} catch (InterruptedException e) {
				//出現中斷異常應該從 cache中移除Future,防止緩存污染
				cache.remove(key,future);
			} catch (ExecutionException e) {
				//執行中的異常應當拋出,得到恰當處理
				throw new RuntimeException(e.getCause());
			}
		}
	}
	
}


下面是一個測試類: 編程

public class Test {
	public static void main(String[] args) {
		final Computable<Integer, Integer> c = new Computable<Integer, Integer>() {
			@Override
			public Integer compute(Integer arg) {
				Integer sum = 0;
				for(Integer i=0;i<arg;i++){
					sum+=i;
				}
				return sum;
			}
		};
		final Computable<Integer, Integer> cache = new FutureCache<Integer,Integer>(c);
		long start = System.currentTimeMillis();
		cache.compute(10000);
		long stop = System.currentTimeMillis();
		System.out.println(stop-start);
		start = System.currentTimeMillis();
		cache.compute(10000);
		stop = System.currentTimeMillis();
		System.out.println(stop-start);
		start = System.currentTimeMillis();
		cache.compute(10000);
		stop = System.currentTimeMillis();
		System.out.println(stop-start);
		start = System.currentTimeMillis();
		cache.compute(10000);
		stop = System.currentTimeMillis();
		System.out.println(stop-start);
	}
}
@絕望的八皮
相關文章
相關標籤/搜索