forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConcurrentHashMap1.java
More file actions
77 lines (59 loc) · 2.36 KB
/
ConcurrentHashMap1.java
File metadata and controls
77 lines (59 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;
/**
* @author Benjamin Winterberg
*/
public class ConcurrentHashMap1 {
public static void main(String[] args) {
System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism());
testForEach();
testSearch();
testReduce();
}
private static void testReduce() {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.putIfAbsent("foo", "bar");
map.putIfAbsent("han", "solo");
map.putIfAbsent("r2", "d2");
map.putIfAbsent("c3", "p0");
String reduced = map.reduce(1, (key, value) -> key + "=" + value,
(s1, s2) -> s1 + ", " + s2);
System.out.println(reduced);
}
private static void testSearch() {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.putIfAbsent("foo", "bar");
map.putIfAbsent("han", "solo");
map.putIfAbsent("r2", "d2");
map.putIfAbsent("c3", "p0");
System.out.println("\nsearch()\n");
String result1 = map.search(1, (key, value) -> {
System.out.println(Thread.currentThread().getName());
if (key.equals("foo") && value.equals("bar")) {
return "foobar";
}
return null;
});
System.out.println(result1);
System.out.println("\nsearchValues()\n");
String result2 = map.searchValues(1, value -> {
System.out.println(Thread.currentThread().getName());
if (value.length() > 3) {
return value;
}
return null;
});
System.out.println(result2);
}
private static void testForEach() {
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.putIfAbsent("foo", "bar");
map.putIfAbsent("han", "solo");
map.putIfAbsent("r2", "d2");
map.putIfAbsent("c3", "p0");
map.forEach(1, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));
// map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));
System.out.println(map.mappingCount());
}
}