Skip to content

Commit

Permalink
avoid virtual thread pinning in RestClientsConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
mariofusco committed Jul 16, 2024
1 parent 75b4ed4 commit 3f1747b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;

import io.quarkus.bootstrap.runner.VirtualThreadSupport;
import jakarta.enterprise.inject.CreationException;

import org.eclipse.microprofile.rest.client.ext.QueryParamStyle;
Expand Down Expand Up @@ -37,7 +40,7 @@ public class RestClientsConfig {
// The @Deprecated annotation prevents this field from being included in generated docs. We only want the `configKey` field
// above to be included.
@Deprecated
private final Map<String, RestClientConfig> configs = new ConcurrentHashMap<>();
private final ConcurrentVThreadMap<String, RestClientConfig> configs = new ConcurrentVThreadMap<>();

/**
* Mode in which the form data are encoded. Possible values are `HTML5`, `RFC1738` and `RFC3986`.
Expand Down Expand Up @@ -363,4 +366,33 @@ public static RestClientsConfig getInstance() {
}
return configHandle.get();
}

private static class ConcurrentVThreadMap<K, V> extends ConcurrentHashMap<K, V> {

private final ReentrantLock lock = new ReentrantLock();

@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (!VirtualThreadSupport.isVirtualThread()) {
return super.computeIfAbsent(key, mappingFunction);
}

V value = get(key);
return value != null ? value : threadSafePutIfAbsent(key, mappingFunction);
}

private V threadSafePutIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
lock.lock();
try {
V value = get(key);
if (value == null) {
value = mappingFunction.apply(key);
put(key, value);
}
return value;
} finally {
lock.unlock();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ private static MethodHandle findVirtualMH() {
}
}

static boolean isVirtualThread() {
public static boolean isVirtualThread() {
if (virtualMh == null) {
return false;
}
Expand All @@ -30,11 +30,11 @@ static boolean isVirtualThread() {
}
}

static int majorVersionFromJavaSpecificationVersion() {
private static int majorVersionFromJavaSpecificationVersion() {
return majorVersion(System.getProperty("java.specification.version", "17"));
}

static int majorVersion(String javaSpecVersion) {
private static int majorVersion(String javaSpecVersion) {
String[] components = javaSpecVersion.split("\\.");
int[] version = new int[components.length];

Expand Down

0 comments on commit 3f1747b

Please sign in to comment.