一个可能的问题是,您通过
veryCostlyOperation()在一个
synchronized块内执行来创建不必要的竞争,因此许多线程无法同时检索其(独立)资源。这可以通过使用
Future<Resource>map的值来解决:
Map<String, Future<Resource>> map = new ConcurrentHashMap<String, Future<Resource>>(); ...Future<Resource> r = map.get(name);if (r == null) { FutureTask task = null; synchronized (lock) { r = map.get(name); if (r == null) { task = new FutureTask(new Callable<Resource>() { public Resource call() { return veryCostlyOperation(name); } }); r = task; map.put(name, r); } } if (task != null) task.run(); // Retrieve the resource}return r.get(); // Wait while other thread is retrieving the resource if necessary


