Skip to content

Instantly share code, notes, and snippets.

@dpash
Last active August 29, 2018 20:57
Show Gist options
  • Save dpash/bb5bd8a0720ba42c5f5dba68ab334317 to your computer and use it in GitHub Desktop.
Save dpash/bb5bd8a0720ba42c5f5dba68ab334317 to your computer and use it in GitHub Desktop.
public class CounterConcurrentHashMap<K> {
private final Map<K, MutableInteger> counters = new ConcurrentHashMap<>();
public int up(K key) {
MutableInteger initValue = new MutableInteger(1);
MutableInteger oldValue = counters.put(key, initValue);
if (oldValue != null) {
initValue.set(oldValue.get() + 1);
}
return initValue.get();
}
public int getCount(K key) {
return counters.getOrDefault(key, new MutableInteger(0)).get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment