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 0000000..e69de29 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 0000000..18d1b01 --- /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 0000000..85ea3aa --- /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 6a1d53d..1988de2 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