io.funtom.util.concurrent.ConcurrencySegment Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
A Java utils library, contains common utils
package io.funtom.util.concurrent;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
final class ConcurrencySegment {
private final Map store = new HashMap();
private final Supplier valuesSupplier;
ConcurrencySegment(Supplier valuesSupplier) {
this.valuesSupplier = valuesSupplier;
}
synchronized V getValue(K key) {
Entry current = store.get(key);
if (current == null) {
current = new Entry();
store.put(key, current);
} else {
current.users++;
}
return current.value;
}
synchronized void releaseKey(K key) {
Entry current = store.get(key);
if (current.users == 1) {
store.remove(key);
} else {
current.users--;
}
}
private class Entry {
private int users = 1;
private V value = valuesSupplier.get();
}
}