com.netflix.hystrix.util.InternMap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hystrix-core Show documentation
Show all versions of hystrix-core Show documentation
hystrix-core developed by Netflix
package com.netflix.hystrix.util;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Utility to have 'intern' - like functionality, which holds single instance of wrapper for a given key
*/
public class InternMap {
private final ConcurrentMap storage = new ConcurrentHashMap();
private final ValueConstructor valueConstructor;
public interface ValueConstructor {
V create(K key);
}
public InternMap(ValueConstructor valueConstructor) {
this.valueConstructor = valueConstructor;
}
public V interned(K key) {
V existingKey = storage.get(key);
V newKey = null;
if (existingKey == null) {
newKey = valueConstructor.create(key);
existingKey = storage.putIfAbsent(key, newKey);
}
return existingKey != null ? existingKey : newKey;
}
public int size() {
return storage.size();
}
}