com.pamirs.pradar.scope.ConcurrentPool Maven / Gradle / Ivy
package com.pamirs.pradar.scope;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Created by xiaobin on 2017/1/19.
*/
public class ConcurrentPool implements Pool {
private final ConcurrentMap pool = new ConcurrentHashMap(500, 0.9f);
private final PoolObjectFactory objectFactory;
public ConcurrentPool(PoolObjectFactory objectFactory) {
if (objectFactory == null) {
throw new NullPointerException("objectFactory must not be null");
}
this.objectFactory = objectFactory;
}
@Override
public V get(K key) {
if (key == null) {
throw new IllegalArgumentException("key must not be null");
}
final V alreadyExist = this.pool.get(key);
if (alreadyExist != null) {
return alreadyExist;
}
final V newValue = this.objectFactory.create(key);
final V oldValue = this.pool.putIfAbsent(key, newValue);
if (oldValue != null) {
return oldValue;
}
return newValue;
}
}