|
| 1 | +package cn.byhieg.java8.concurrent; |
| 2 | + |
| 3 | +import java.util.concurrent.ConcurrentHashMap; |
| 4 | +import java.util.concurrent.ForkJoinPool; |
| 5 | + |
| 6 | +/** |
| 7 | + * @author Benjamin Winterberg |
| 8 | + */ |
| 9 | +public class ConcurrentHashMap1 { |
| 10 | + |
| 11 | + public static void main(String[] args) { |
| 12 | + System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism()); |
| 13 | + |
| 14 | + testForEach(); |
| 15 | + testSearch(); |
| 16 | + testReduce(); |
| 17 | + } |
| 18 | + |
| 19 | + private static void testReduce() { |
| 20 | + ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(); |
| 21 | + map.putIfAbsent("foo", "bar"); |
| 22 | + map.putIfAbsent("han", "solo"); |
| 23 | + map.putIfAbsent("r2", "d2"); |
| 24 | + map.putIfAbsent("c3", "p0"); |
| 25 | + |
| 26 | + String reduced = map.reduce(1, (key, value) -> key + "=" + value, |
| 27 | + (s1, s2) -> s1 + ", " + s2); |
| 28 | + |
| 29 | + System.out.println(reduced); |
| 30 | + } |
| 31 | + |
| 32 | + private static void testSearch() { |
| 33 | + ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(); |
| 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 | + String result1 = 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 | + return null; |
| 47 | + }); |
| 48 | + |
| 49 | + System.out.println(result1); |
| 50 | + |
| 51 | + System.out.println("\nsearchValues()\n"); |
| 52 | + |
| 53 | + String result2 = map.searchValues(1, value -> { |
| 54 | + System.out.println(Thread.currentThread().getName()); |
| 55 | + if (value.length() > 3) { |
| 56 | + return value; |
| 57 | + } |
| 58 | + return null; |
| 59 | + }); |
| 60 | + |
| 61 | + System.out.println(result2); |
| 62 | + } |
| 63 | + |
| 64 | + private static void testForEach() { |
| 65 | + ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(); |
| 66 | + map.putIfAbsent("foo", "bar"); |
| 67 | + map.putIfAbsent("han", "solo"); |
| 68 | + map.putIfAbsent("r2", "d2"); |
| 69 | + map.putIfAbsent("c3", "p0"); |
| 70 | + |
| 71 | + map.forEach(1, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName())); |
| 72 | +// map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName())); |
| 73 | + |
| 74 | + System.out.println(map.mappingCount()); |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments