Skip to content

Instantly share code, notes, and snippets.

@nielsutrecht
Last active August 29, 2018 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielsutrecht/0e0e01df8bfcbf45307a93813fa2e0db to your computer and use it in GitHub Desktop.
Save nielsutrecht/0e0e01df8bfcbf45307a93813fa2e0db to your computer and use it in GitHub Desktop.
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Test {
public static class MutableInteger {
private int val;
public MutableInteger() {
this(0);
}
public MutableInteger(int val) {
this.val = val;
}
public int get() {
return val;
}
public void set(int val) {
this.val = val;
}
}
public static class CounterConcurrentHashMap<K> extends ConcurrentHashMap<K, MutableInteger> {
public MutableInteger up(K key) {
MutableInteger initValue = new MutableInteger(1);
MutableInteger oldValue = super.put(key, initValue);
if(oldValue != null) {
initValue.set(oldValue.get() + 1);
}
return initValue;
}
}
public static void main(String... argv) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(8);
CounterConcurrentHashMap<String> map = new CounterConcurrentHashMap<>();
List<Future> futures = IntStream.range(0, 8).mapToObj(i -> pool.submit(() -> {
for(int j = 0;j < 1000000;j++) {
map.up("key");
}
})).collect(Collectors.toList());
for(Future f : futures) {
f.get();
}
System.out.println(map.get("key").get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment