是。Google Collections或Guava的名称现在有了一个叫做MapMaker的东西,可以做到这一点。
ConcurrentMap<Key, Graph> graphs = new MapMaker() .concurrencyLevel(4) .softKeys() .weakValues() .maximumSize(10000) .expiration(10, TimeUnit.MINUTES) .makeComputingMap( new Function<Key, Graph>() { public Graph apply(Key key) {return createExpensiveGraph(key); } });更新:
从guava 10.0(2011年9月28日发布)开始,许多MapMaker方法已被弃用,以支持新的CacheBuilder:LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder() .maximumSize(10000) .expireAfterWrite(10, TimeUnit.MINUTES) .build( new CacheLoader<Key, Graph>() { public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } });


