|
9 | 9 | publicclassConcurrentHashMap1 {
|
10 | 10 |
|
11 | 11 | publicstaticvoidmain(String[]args) {
|
| 12 | +System.out.println("Parallelism: " +ForkJoinPool.getCommonPoolParallelism()); |
| 13 | + |
12 | 14 | testForEach();
|
| 15 | +testSearch(); |
| 16 | +testReduce(); |
13 | 17 | }
|
14 | 18 |
|
15 |
| -privatestaticvoidtestForEach() { |
| 19 | +privatestaticvoidtestReduce() { |
16 | 20 | ConcurrentHashMap<String,String>map =newConcurrentHashMap<>();
|
17 | 21 | map.putIfAbsent("foo","bar");
|
18 | 22 | map.putIfAbsent("han","solo");
|
19 | 23 | map.putIfAbsent("r2","d2");
|
20 | 24 | map.putIfAbsent("c3","p0");
|
21 | 25 |
|
| 26 | +Stringreduced =map.reduce(1, (key,value) ->key +"=" +value, |
| 27 | + (s1,s2) ->s1 +", " +s2); |
22 | 28 |
|
23 |
| -// map.forEach((key, value) -> System.out.printf("key: %s; value: %s\n", key, value)); |
| 29 | +System.out.println(reduced); |
| 30 | + } |
24 | 31 |
|
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"); |
26 | 70 |
|
27 | 71 | map.forEach(1, (key,value) ->System.out.printf("key: %s; value: %s; thread: %s\n",key,value,Thread.currentThread().getName()));
|
28 | 72 | // map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));
|
|