From 3fc51075792cfc85c1bca478d18eb2cc1cd497af Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 5 Aug 2024 10:38:11 +0200 Subject: [PATCH] ConcurrentHashMap#computeIfAbsent --- .../README.MD | 0 java-concurrent-hm-compute-if-absent/pom.xml | 22 ++++++++++++ .../pivovarit/chm/ComputeIfAbsentExample.java | 35 +++++++++++++++++++ pom.xml | 1 + 4 files changed, 58 insertions(+) create mode 100644 java-concurrent-hm-compute-if-absent/README.MD create mode 100644 java-concurrent-hm-compute-if-absent/pom.xml create mode 100644 java-concurrent-hm-compute-if-absent/src/main/java/com/pivovarit/chm/ComputeIfAbsentExample.java diff --git a/java-concurrent-hm-compute-if-absent/README.MD b/java-concurrent-hm-compute-if-absent/README.MD new file mode 100644 index 00000000..e69de29b diff --git a/java-concurrent-hm-compute-if-absent/pom.xml b/java-concurrent-hm-compute-if-absent/pom.xml new file mode 100644 index 00000000..18d1b01b --- /dev/null +++ b/java-concurrent-hm-compute-if-absent/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + + com.pivovarit + 1.0 + java-concurrent-hm-compute-if-absent + + java-concurrent-hm-compute-if-absent + + + + org.apache.maven.plugins + maven-compiler-plugin + + 21 + 21 + + + + + diff --git a/java-concurrent-hm-compute-if-absent/src/main/java/com/pivovarit/chm/ComputeIfAbsentExample.java b/java-concurrent-hm-compute-if-absent/src/main/java/com/pivovarit/chm/ComputeIfAbsentExample.java new file mode 100644 index 00000000..85ea3aae --- /dev/null +++ b/java-concurrent-hm-compute-if-absent/src/main/java/com/pivovarit/chm/ComputeIfAbsentExample.java @@ -0,0 +1,35 @@ +package com.pivovarit.chm; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; + +class ComputeIfAbsentExample { + + public static void main(String[] args) { + var map = new ConcurrentHashMap<>(1024); + var counter = new AtomicInteger(); + Stream.of(1, 2) + .map(tid -> Thread.ofPlatform().start(() -> { + for (int i = 0; i < 10; i++) { + int key = ThreadLocalRandom.current().nextInt(10); + map.computeIfAbsent(key, s -> { + if (counter.incrementAndGet() > 1) { + System.out.println("I told you so!"); + } + doWork(); + counter.decrementAndGet(); + return key; + }); + } + })).forEach(t -> {}); + } + + private static void doWork() { + try { + Thread.sleep(100); + } catch (InterruptedException ignored) { + } + } +} diff --git a/pom.xml b/pom.xml index 6a1d53d9..1988de2f 100644 --- a/pom.xml +++ b/pom.xml @@ -24,6 +24,7 @@ java-archunit java-sealed-classes java-completable-future-timeouts + java-concurrent-hm-compute-if-absent java-event-sourcing java-completable-future-allof java-advanced-groupingby