Last active
August 29, 2018 12:46
-
-
Save nielsutrecht/0e0e01df8bfcbf45307a93813fa2e0db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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