Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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