Java并发编程实战中提到的一个简单的缓存系统

本文介绍了一个在Java并发编程环境下实现简单缓存系统的实现方式,通过使用Future和ConcurrentHashMap来提高程序效率并减少资源浪费。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是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);
	}
}
@绝望的八皮

转载于:https://my.oschina.net/ccdvote/blog/131876

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值