针对下面程序,设计一个缓存 其中Thread.sleep休眠10s来替代一些耗时任务,有并发获取和写入(写入代码没有提供)
public Integer get(int id) { // TODO: cache try { Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } return new Random(id).nextInt(); }
基础要求:
1、使用软引用+ConcurrentHashMap实现
2、软引用+HashMap+ReentrantReadWriteLock实现
public abstract class AbstractCache { public abstract Integer get(int id) throws Exception; }
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.Random; import java.util.concurrent.ExecutionException; public class Cache extends AbstractCache{ private static final LoadingCache<String, Integer> cache = CacheBuilder.newBuilder() .build(new CacheLoader<String, Integer>() { @Override public Integer load(String s) throws Exception { try { Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } int value = new Random(Integer.parseInt(s)).nextInt(); return value; } }); @Override public Integer get(int id) throws ExecutionException { String key = String.valueOf(id); Integer value = cache.get(key); return value; } }
import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; public class Cache1 extends AbstractCache { private static final Cache<String, Integer> cache = CacheBuilder.newBuilder().maximumSize(1000).build(); @Override public Integer get(int id) throws ExecutionException { String key = String.valueOf(id); Integer value = cache.get(key, new Callable<Integer>() { @Override public Integer call() throws Exception { return doThingsTheHardWay(key); } }); return value; } public static Integer doThingsTheHardWay(String s) { return new Random(Integer.parseInt(s)).nextInt(); } public static void main(String[] args) throws ExecutionException { System.out.println( new Cache1().get(3)); System.out.println( new Cache1().get(3)); System.out.println( new Cache1().get(3)); } }