Skip to content

Commit

Permalink
ConcurrentHashMap#computeIfAbsent
Browse files Browse the repository at this point in the history
  • Loading branch information
pivovarit committed Aug 5, 2024
1 parent 38f3489 commit 3fc5107
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 0 deletions.
Empty file.
22 changes: 22 additions & 0 deletions java-concurrent-hm-compute-if-absent/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.pivovarit</groupId>
<version>1.0</version>
<artifactId>java-concurrent-hm-compute-if-absent</artifactId>

<name>java-concurrent-hm-compute-if-absent</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -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) {
}
}
}
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<module>java-archunit</module>
<module>java-sealed-classes</module>
<module>java-completable-future-timeouts</module>
<module>java-concurrent-hm-compute-if-absent</module>
<module>java-event-sourcing</module>
<module>java-completable-future-allof</module>
<module>java-advanced-groupingby</module>
Expand Down

0 comments on commit 3fc5107

Please sign in to comment.