public class MyServlet extends Servlet{ private static Map<String, String> fileName2Data = new HashMap<String, String>(); private void processFile3(String fName){ String data = fileName2Data.get(fName); if(data==null){ data = readFromFile(fName); //耗时28ms fileName2Data.put(fName, data); } //process with data } }
public class MyServlet extends Servlet{ private static ConcurrentHashMap<String, String> fileName2Data = new ConcurrentHashMap<String, String>(); private void processFile3(String fName){ String data = fileName2Data.get(fName); if(data==null){ data = readFromFile(fName); //耗时28ms fileName2Data.put(fName, data); } //process with data } }
public class MyServlet extends Servlet{ private static ConcurrentHashMap<String, String> fileName2Data = new ConcurrentHashMap<String, String>(); private void processFile3(String fName){ String data = fileName2Data.get(fName); //“偶然”-- 1000个线程同时到这里,同时发现data为null if(data==null){ data = readFromFile(fName); //耗时28ms fileName2Data.put(fName, data); } //process with data } }
public class MyServlet extends Servlet{ private static ConcurrentHashMap<String, FutureTask> fileName2Data = new ConcurrentHashMap<String, FutureTask>(); private static ExecutorService exec = Executors.newCacheThreadPool(); private void processFile3(String fName){ FutureTask data = fileName2Data.get(fName); //“偶然”-- 1000个线程同时到这里,同时发现data为null if(data==null){ data = newFutureTask(fName); FutureTask old = fileName2Data.putIfAbsent(fName, data); if(old==null){ data = old; }else{ exec.execute(data); } } String d = data.get(); //process with data } private FutureTask newFutureTask(final String file){ return new FutureTask(new Callable<String>(){ public String call(){ return readFromFile(file); } private String readFromFile(String file){return "";} } } }
END 十期推荐 【201期】面试官:String长度有限制吗?是多少?还好我看过 【202期】面试官:GET 和 POST请求的本质区别是什么?(本质没区别) 【203期】吃透Java IO:字节流、字符流、缓冲流 【204期】面试官:你手写过堵塞队列吗? 【205期】面试官:数据量很大的情况下,对于分页查询你有什么优化方案吗? 【206期】面试官:你的项目是如何处理重复请求/并发请求的? 【207期】19张图带你梳理SpringCloud体系中的重要知识点! 【208期】敲黑板,也来谈如何设计一个秒杀系统(重点) 【209期】架构设计&分布式&数据结构与算法面试题(2020最新版) 【210期】面试官:说说常用的Redis和zk两种分布式锁的对比 ? ~