Skip to content

Commit c80d39b

Browse files
committed
ConcurrentHashMap examples
1 parent 97c2081 commit c80d39b

File tree

1 file changed

+47
-3
lines changed

1 file changed

+47
-3
lines changed

‎src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,64 @@
99
publicclassConcurrentHashMap1{
1010

1111
publicstaticvoidmain(String[] args){
12+
System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism());
13+
1214
testForEach();
15+
testSearch();
16+
testReduce();
1317
}
1418

15-
privatestaticvoidtestForEach(){
19+
privatestaticvoidtestReduce(){
1620
ConcurrentHashMap<String, String> map = newConcurrentHashMap<>();
1721
map.putIfAbsent("foo", "bar");
1822
map.putIfAbsent("han", "solo");
1923
map.putIfAbsent("r2", "d2");
2024
map.putIfAbsent("c3", "p0");
2125

26+
Stringreduced = map.reduce(1, (key, value) -> key + "=" + value,
27+
(s1, s2) -> s1 + ", " + s2);
2228

23-
// map.forEach((key, value) -> System.out.printf("key: %s; value: %s\n", key, value));
29+
System.out.println(reduced);
30+
}
2431

25-
System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism());
32+
privatestaticvoidtestSearch(){
33+
ConcurrentHashMap<String, String> map = newConcurrentHashMap<>();
34+
map.putIfAbsent("foo", "bar");
35+
map.putIfAbsent("han", "solo");
36+
map.putIfAbsent("r2", "d2");
37+
map.putIfAbsent("c3", "p0");
38+
39+
System.out.println("\nsearch()\n");
40+
41+
Stringresult1 = map.search(1, (key, value) ->{
42+
System.out.println(Thread.currentThread().getName());
43+
if (key.equals("foo") && value.equals("bar")){
44+
return"foobar";
45+
}
46+
returnnull;
47+
});
48+
49+
System.out.println(result1);
50+
51+
System.out.println("\nsearchValues()\n");
52+
53+
Stringresult2 = map.searchValues(1, value ->{
54+
System.out.println(Thread.currentThread().getName());
55+
if (value.length() > 3){
56+
returnvalue;
57+
}
58+
returnnull;
59+
});
60+
61+
System.out.println(result2);
62+
}
63+
64+
privatestaticvoidtestForEach(){
65+
ConcurrentHashMap<String, String> map = newConcurrentHashMap<>();
66+
map.putIfAbsent("foo", "bar");
67+
map.putIfAbsent("han", "solo");
68+
map.putIfAbsent("r2", "d2");
69+
map.putIfAbsent("c3", "p0");
2670

2771
map.forEach(1, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));
2872
// map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));

0 commit comments

Comments
(0)