Skip to content

Commit

Permalink
Replace synchronized block with ReentrantLock (#208)
Browse files Browse the repository at this point in the history
Replace synchronized block with ReentrantLock to avoid possible thread pinning with VirtualThreads (Java 21)
  • Loading branch information
ofaizulin authored Sep 8, 2024
1 parent 2cd444f commit 4cba70e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.Map;
import java.util.Objects;

import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -29,7 +30,7 @@ abstract class ProcfsEntry {

private static final long CACHE_DURATION_MS = 1000;

private final Object lock = new Object();
private final ReentrantLock lock = new ReentrantLock();

private final ProcfsReader reader;

Expand Down Expand Up @@ -58,7 +59,8 @@ public Double get(ValueKey key) {
if (lastHandle != -1 && lastHandle + CACHE_DURATION_MS > currentTime()) {
return;
}
synchronized (lock) {
try {
lock.lock();
if (lastHandle != -1 && lastHandle + CACHE_DURATION_MS > currentTime()) {
return;
}
Expand All @@ -73,6 +75,8 @@ public Double get(ValueKey key) {
values.clear();
log.warn("Failed reading '" + reader.getEntryPath() + "'!", e);
}
} finally {
lock.unlock();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

import org.slf4j.Logger;
Expand All @@ -35,7 +36,7 @@ class ProcfsReader {

private static final Map<String, ProcfsReader> instances = new HashMap<>();

private static final Object instancesLock = new Object();
private static final ReentrantLock instancesLock = new ReentrantLock();

private static final Path BASE = Paths.get("/proc", "self");

Expand Down Expand Up @@ -93,8 +94,11 @@ private void readPath(Path path, Consumer<String> consumer) throws IOException {
/* default */ static ProcfsReader getInstance(String entry) {
Objects.requireNonNull(entry);

synchronized (instancesLock) {
try {
instancesLock.lock();
return instances.computeIfAbsent(entry, e -> new ProcfsReader(e));
} finally{
instancesLock.unlock();
}
}

Expand Down

0 comments on commit 4cba70e

Please sign in to comment.