Java Code Examples for java.util.concurrent.ConcurrentHashMap#forEach()
The following examples show how to use
java.util.concurrent.ConcurrentHashMap#forEach() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Concurrency1.java From javacore with Creative Commons Attribution Share Alike 4.0 International | 9 votes |
public static void main(String[] args) { ConcurrentHashMap<Integer, UUID> concurrentHashMap = new ConcurrentHashMap<>(); for (int i = 0; i < 100; i++) { concurrentHashMap.put(i, UUID.randomUUID()); } int threshold = 1; concurrentHashMap.forEachValue(threshold, System.out::println); concurrentHashMap.forEach((id, uuid) -> { if (id % 10 == 0) { System.out.println(String.format("%s: %s", id, uuid)); } }); UUID searchResult = concurrentHashMap.search(threshold, (id, uuid) -> { if (String.valueOf(uuid).startsWith(String.valueOf(id))) { return uuid; } return null; }); System.out.println(searchResult); }
Example 2
Source File: HttpHandler.java From smartacus-mqtt-broker with Apache License 2.0 | 6 votes |
private void getConnections(ChannelHandlerContext ctx, ConcurrentHashMap<String,ClientConnection> connectionFactory) { ArrayList<ClientConnectionVO> vos = new ArrayList<>(); if(null !=connectionFactory && !connectionFactory.isEmpty()){ connectionFactory.forEach((k,v)->{ ClientConnectionVO vo=new ClientConnectionVO(); vo.setClientId(v.getClientId()); vo.setUsername(v.getUsername()); vo.setIp(v.getIp()); vo.setPort(v.getPort()); vo.setConnectedDate(v.getConnectedDate()); vo.setProtocolVersion(v.getProtocolVersion()); vo.setPassword(v.getPassword()); vos.add(vo); }); } // 1.设置响应 Result result= new Result<Object>().ok(vos); FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(JSONObject.toJSONString(result), CharsetUtil.UTF_8)); resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); // 2.发送 // 注意必须在使用完之后,close channel ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE); }
Example 3
Source File: ClientGroupManager.java From smartacus-mqtt-broker with Apache License 2.0 | 6 votes |
public static void sendOffLineGroupMessage(String groupId){ ClientGroup clientGroup = group.get(groupId); if(clientGroup!=null){ ConcurrentHashMap<String, Channel> clients = clientGroup.subOfflineClients; clients.forEach((K,V)->{ MqttFixedHeader pubFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttPublishVariableHeader publishVariableHeader=new MqttPublishVariableHeader(clientGroup.offLineTopic,1); ByteBuf payload = Unpooled.buffer(200); payload.writeBytes("下线消息".getBytes()); MqttPublishMessage pubMsg=new MqttPublishMessage(pubFixedHeader,publishVariableHeader,payload); V.writeAndFlush(pubMsg); System.out.println("=============群发下线消息==============="); }); } }
Example 4
Source File: Concurrency1.java From java8-tutorial with MIT License | 6 votes |
public static void main(String[] args) { ConcurrentHashMap<Integer, UUID> concurrentHashMap = new ConcurrentHashMap<>(); for (int i = 0; i < 100; i++) { concurrentHashMap.put(i, UUID.randomUUID()); } int threshold = 1; concurrentHashMap.forEachValue(threshold, System.out::println); concurrentHashMap.forEach((id, uuid) -> { if (id % 10 == 0) { System.out.println(String.format("%s: %s", id, uuid)); } }); UUID searchResult = concurrentHashMap.search(threshold, (id, uuid) -> { if (String.valueOf(uuid).startsWith(String.valueOf(id))) { return uuid; } return null; }); System.out.println(searchResult); }
Example 5
Source File: ShardedScheduler.java From elasticactors with Apache License 2.0 | 5 votes |
@Override public void unregisterShard(ShardKey shardKey) { ConcurrentHashMap<ScheduledMessageKey, ScheduledFuture<?>> scheduledFuturesForShard = scheduledFutures.remove(shardKey); if (scheduledFuturesForShard != null) { scheduledFuturesForShard.forEach((k, scheduledFuture) -> scheduledFuture.cancel(false)); } }
Example 6
Source File: Main.java From Java-Coding-Problems with MIT License | 5 votes |
public static void main(String[] args) { ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>(); map.put(1, 1); map.put(2, 1); map.put(3, 1); map.put(4, 1); map.put(5, 1); map.put(6, 1); System.out.println("Map: \n" + map); System.out.println("\nMap displayed via forEach():"); map.forEach(2, (k, v) -> System.out.println("key: " + k + ", Value: " + v)); System.out.println("\nMap displayed via forEach() after incrementing each value with 1:"); map.forEach(2, (k, v) -> v = v + 1, v -> System.out.println("Value: " + v)); System.out.println("\nMap displayed via forEachEntry():"); map.forEachEntry(2, (e) -> System.out.println("key: " + e.getKey() + ", Value: " + e.getValue())); System.out.println("\nCheck if key=value via forEachEntry():"); map.forEachEntry(2, (e) -> Objects.equals(e.getKey(), e.getValue()), System.out::println); System.out.println("\nDisplay keys via forEachKey():"); map.forEachKey(2, System.out::println); System.out.println("\nKeys displayed via forEachKey() after incrementing each key with 1:"); map.forEachKey(2, (k) -> k = k + 1, System.out::println); System.out.println("\nDisplay values via forEachValue():"); map.forEachValue(2, System.out::println); System.out.println("\nKeys displayed via forEachValue() after incrementing each value with 1:"); map.forEachValue(2, (v) -> v = v + 1, System.out::println); }
Example 7
Source File: ConcurrentHashMap1.java From java8-tutorial with MIT License | 5 votes |
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()); }
Example 8
Source File: ConcurrentHashMap8Test.java From j2objc with Apache License 2.0 | 5 votes |
/** * forEachInParallel traverses all mappings */ public void testForEachInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEach(1L, (Long x, Long y) -> adder.add(x.longValue() + y.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); }
Example 9
Source File: ConcurrentHashMap8Test.java From j2objc with Apache License 2.0 | 5 votes |
/** * forEachSequentially traverses all mappings */ public void testForEachSequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEach(Long.MAX_VALUE, (Long x, Long y) -> adder.add(x.longValue() + y.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); }
Example 10
Source File: ConcurrentHashMap8Test.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * forEachInParallel traverses all mappings */ public void testForEachInParallel() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEach(1L, (Long x, Long y) -> adder.add(x.longValue() + y.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); }
Example 11
Source File: ConcurrentHashMap8Test.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * forEachSequentially traverses all mappings */ public void testForEachSequentially() { LongAdder adder = new LongAdder(); ConcurrentHashMap<Long, Long> m = longMap(); m.forEach(Long.MAX_VALUE, (Long x, Long y) -> adder.add(x.longValue() + y.longValue())); assertEquals(adder.sum(), 3 * SIZE * (SIZE - 1) / 2); }
Example 12
Source File: CleanerTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Example using a Cleaner to remove WeakKey references from a Map. */ @Test void testWeakKey() { ConcurrentHashMap<WeakKey<String>, String> map = new ConcurrentHashMap<>(); Cleaner cleaner = Cleaner.create(); String key = new String("foo"); // ensure it is not interned String data = "bar"; map.put(new WeakKey<>(key, cleaner, map), data); WeakKey<String> k2 = new WeakKey<>(key, cleaner, map); Assert.assertEquals(map.get(k2), data, "value should be found in the map"); key = null; System.gc(); Assert.assertNotEquals(map.get(k2), data, "value should not be found in the map"); final long CYCLE_MAX = Utils.adjustTimeout(30L); for (int i = 1; map.size() > 0 && i < CYCLE_MAX; i++) { map.forEach( (k, v) -> System.out.printf(" k: %s, v: %s%n", k, v)); try { Thread.sleep(10L); } catch (InterruptedException ie) {} } Assert.assertEquals(map.size(), 0, "Expected map to be empty;"); cleaner = null; }
Example 13
Source File: ConcurrentHashMap1.java From javacore with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
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()); }
Example 14
Source File: ProgMainExecServConcurrentHashMap09.java From javase with MIT License | 5 votes |
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()); }
Example 15
Source File: ConcurrentMapTest.java From java-tutorial with MIT License | 5 votes |
/** * ConcurrentMap接口继承自Map接口,并定义了最实用的并发集合类型之一。 * Java8通过将新的方法添加到这个接口,引入了函数式编程。 * ConcurrentHashMap 是无序的 */ public void concurrentMapDemo() { ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>(); map.put("foo", "bar"); map.put("han", "solo"); map.put("r2", "d2"); map.put("c3", "p0"); // 方法可以并行迭代映射中的键值对 map.forEach(1, (k, v) -> System.out.printf("key: %s; value: %s; thread: %s\n", k, v, Thread.currentThread().getName())); System.out.println("\n"); // search 只要返回了非空的结果,就不会往下搜索了 String result = map.search(1, (k, v) -> { System.out.println(Thread.currentThread().getName()); if ("foo".equals(k)) { return v; } return null; } ); System.out.println("Result: " + result); System.out.println("\n"); String result1 = map.search(1, (k, v) -> { System.out.println(Thread.currentThread().getName()); if (v.length() > 3) { return v; } return null; } ); System.out.println("Result: " + result1); System.out.println("\n"); String result2 = map.reduce(1, (k, v) -> { System.out.println("Transform: " + Thread.currentThread().getName()); return k + "=" + v; }, (s1, s2) -> { System.out.println("Reduce: " + Thread.currentThread().getName()); return s1 + ", " + s2; } ); System.out.println("Result: " + result2); }
Example 16
Source File: TreeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * A test for scale; launch a large number (14) of subprocesses. */ @Test public static void test5() { ConcurrentHashMap<ProcessHandle, ProcessHandle> processes = new ConcurrentHashMap<>(); int factor = 2; JavaChild p1 = null; Instant start = Instant.now(); try { p1 = JavaChild.spawnJavaChild("stdin"); ProcessHandle p1Handle = p1.toHandle(); printf("Spawning %d x %d x %d processes, pid: %d%n", factor, factor, factor, p1.pid()); // Start the first tier of subprocesses p1.sendAction("spawn", factor, "stdin"); // Start the second tier of subprocesses p1.sendAction("child", "spawn", factor, "stdin"); // Start the third tier of subprocesses p1.sendAction("child", "child", "spawn", factor, "stdin"); int newChildren = factor * (1 + factor * (1 + factor)); CountDownLatch spawnCount = new CountDownLatch(newChildren); // Gather the PIDs from the output of the spawning process p1.forEachOutputLine((s) -> { String[] split = s.trim().split(" "); if (split.length == 3 && split[1].equals("spawn")) { Long child = Long.valueOf(split[2]); Long parent = Long.valueOf(split[0].split(":")[0]); processes.put(ProcessHandle.of(child).get(), ProcessHandle.of(parent).get()); spawnCount.countDown(); } }); // Wait for all the subprocesses to be listed as started Assert.assertTrue(spawnCount.await(Utils.adjustTimeout(30L), TimeUnit.SECONDS), "Timeout waiting for processes to start"); // Debugging; list descendants that are not expected in processes List<ProcessHandle> descendants = ProcessUtil.getDescendants(p1Handle); long count = descendants.stream() .filter(ph -> !processes.containsKey(ph)) .count(); if (count > 0) { descendants.stream() .filter(ph -> !processes.containsKey(ph)) .forEach(ph1 -> ProcessUtil.printProcess(ph1, "Extra process: ")); ProcessUtil.logTaskList(); Assert.assertEquals(0, count, "Extra processes in descendants"); } Assert.assertEquals(getChildren(p1Handle).size(), factor, "expected direct children"); count = getDescendants(p1Handle).size(); long totalChildren = factor * factor * factor + factor * factor + factor; Assert.assertTrue(count >= totalChildren, "expected at least " + totalChildren + ", actual: " + count); List<ProcessHandle> subprocesses = getDescendants(p1Handle); printf(" descendants: %s%n", subprocesses.stream().map(p -> p.pid()) .collect(Collectors.toList())); p1.getOutputStream().close(); // Close stdin for the controlling p1 p1.waitFor(); } catch (InterruptedException | IOException ex) { Assert.fail("Unexpected Exception", ex); } finally { printf("Duration: %s%n", Duration.between(start, Instant.now())); if (p1 != null) { p1.destroyForcibly(); } processes.forEach((p, parent) -> { if (p.isAlive()) { ProcessUtil.printProcess(p, "Process Cleanup: "); p.destroyForcibly(); } }); } }
Example 17
Source File: TreeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * Test destroy of processes. * A JavaChild is started and it starts three children. * Each one is then checked to be alive and listed by descendants * and forcibly destroyed. * After they exit they should no longer be listed by descendants. */ @Test public static void test3() { ConcurrentHashMap<ProcessHandle, ProcessHandle> processes = new ConcurrentHashMap<>(); try { ProcessHandle self = ProcessHandle.current(); JavaChild p1 = JavaChild.spawnJavaChild("stdin"); ProcessHandle p1Handle = p1.toHandle(); printf(" p1: %s%n", p1.pid()); int newChildren = 3; CountDownLatch spawnCount = new CountDownLatch(newChildren); // Spawn children and have them wait p1.sendAction("spawn", newChildren, "stdin"); // Gather the PIDs from the output of the spawning process p1.forEachOutputLine((s) -> { String[] split = s.trim().split(" "); if (split.length == 3 && split[1].equals("spawn")) { Long child = Long.valueOf(split[2]); Long parent = Long.valueOf(split[0].split(":")[0]); processes.put(ProcessHandle.of(child).get(), ProcessHandle.of(parent).get()); spawnCount.countDown(); } }); // Wait for all the subprocesses to be listed as started Assert.assertTrue(spawnCount.await(Utils.adjustTimeout(30L), TimeUnit.SECONDS), "Timeout waiting for processes to start"); // Debugging; list descendants that are not expected in processes List<ProcessHandle> descendants = ProcessUtil.getDescendants(p1Handle); long count = descendants.stream() .filter(ph -> !processes.containsKey(ph)) .count(); if (count > 0) { descendants.stream() .filter(ph -> !processes.containsKey(ph)) .forEach(ph1 -> ProcessUtil.printProcess(ph1, "Extra process: ")); ProcessUtil.logTaskList(); Assert.assertEquals(0, count, "Extra processes in descendants"); } // Verify that all spawned children are alive, show up in the descendants list // then destroy them processes.forEach((p, parent) -> { Assert.assertEquals(p.isAlive(), true, "Child should be alive: " + p); Assert.assertTrue(descendants.contains(p), "Spawned child should be listed in descendants: " + p); p.destroyForcibly(); }); Assert.assertEquals(processes.size(), newChildren, "Wrong number of children"); // Wait for each of the processes to exit processes.forEach((p, parent) -> { for (long retries = Utils.adjustTimeout(100L); retries > 0 ; retries--) { if (!p.isAlive()) { return; // not alive, go on to the next } // Wait a bit and retry try { Thread.sleep(100L); } catch (InterruptedException ie) { // try again } } printf("Timeout waiting for exit of pid %s, parent: %s, info: %s%n", p, parent, p.info()); Assert.fail("Process still alive: " + p); }); p1.destroyForcibly(); p1.waitFor(); // Verify that none of the spawned children are still listed by descendants List<ProcessHandle> remaining = getDescendants(self); Assert.assertFalse(remaining.remove(p1Handle), "Child p1 should have exited"); remaining = remaining.stream().filter(processes::containsKey).collect(Collectors.toList()); Assert.assertEquals(remaining.size(), 0, "Subprocess(es) should have exited: " + remaining); } catch (IOException ioe) { Assert.fail("Spawn of subprocess failed", ioe); } catch (InterruptedException inte) { Assert.fail("InterruptedException", inte); } finally { processes.forEach((p, parent) -> { if (p.isAlive()) { ProcessUtil.printProcess(p); p.destroyForcibly(); } }); } }