如果为要缓存的内容临时拥有多个实例是安全的,则可以执行“无锁”缓存,如下所示:
public Heavy instance(Object key) { Heavy info = infoMap.get(key); if ( info == null ) { // It's OK to construct a Heavy that ends up not being used info = new Heavy(key); Heavy putByOtherThreadJustNow = infoMap.putIfAbsent(key, info); if ( putByOtherThreadJustNow != null ) { // Some other thread "won" info = putByOtherThreadJustNow; } else { // This thread was the winner } } return info;}多个线程可以“竞争”来创建和添加密钥项,但是只有一个应该“获胜”。



