实现思路
- 定义一个用于计算功能的顶级接口 ,在接口类定义,计算的接口
- 具体的计算器 ,都去实现这个接口
- 定义个带有“记忆”功能(缓存)的计算的容器,通过构造方法传递具体的计算器
- 通过ConcurrentHashMap 去缓存计算的入参结果
- 每次计算的时候判断是否有结果已经缓存,有则跳过计算,直接获取上一次的计算结果
顶层类:computale 接口, 定义为函数式接口
package com.ljq.mydemo.thread.compute;
public interface Computable<A,V> {
public V compute(A ags) throws InterruptedException;
}
定义带缓存的计算器容器
package com.ljq.mydemo.thread.compute;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
public class MemoryCompute<A, V> implements Computable<A, V> {
private final Map<A, V> cache = new ConcurrentHashMap<A, V>();
private final Computable<A, V> computable;
public MemoryCompute(Computable<A, V> computable) {
this.computable = computable;
}
@Override
public V compute(A ags) throws InterruptedException {
V result = cache.get(ags);
System.out.println(Thread.currentThread().getId()+": get cache value : "+result + " key is "+ags);
if (Objects.isNull(result)) {
System.out.println(Thread.currentThread().getName()+": get cache fail ,is computing.......");
result = computable.compute(ags);
cache.put(ags, result);
}
return result;
}
}
测试
package com.ljq.mydemo.thread.compute;
import java.math.BigInteger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ComputeTest001 {
public static void main(String[] args) throws InterruptedException {
ExampleCompute compute=new ExampleCompute();
MemoryCompute<String, BigInteger> memoryCompute=new MemoryCompute(compute);
ExecutorService services = Executors.newCachedThreadPool();
for (int i = 0; i <5 ; i++) {
System.out.println("create randomNumber: "+6);
memoryCompute.compute(String.valueOf(6));
}
services.shutdown();
}
}