Skip to content

Commit

Permalink
Performance: Using ReentrantLock instead of synchronized
Browse files Browse the repository at this point in the history
  • Loading branch information
mkarg committed Dec 22, 2024
1 parent cdbc48b commit cf60c62
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions jaxrs-api/src/main/java/jakarta/ws/rs/ext/RuntimeDelegate.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import java.lang.reflect.ReflectPermission;
import java.net.URL;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import jakarta.ws.rs.SeBootstrap;
import jakarta.ws.rs.SeBootstrap.Instance;
Expand All @@ -45,7 +47,7 @@ public abstract class RuntimeDelegate {
* {@link RuntimeDelegate#getInstance()}.
*/
public static final String JAXRS_RUNTIME_DELEGATE_PROPERTY = "jakarta.ws.rs.ext.RuntimeDelegate";
private static final Object RD_LOCK = new Object();
private static final Lock RD_LOCK = new ReentrantLock();
private static ReflectPermission suppressAccessChecksPermission = new ReflectPermission("suppressAccessChecks");
private static volatile RuntimeDelegate cachedDelegate;

Expand Down Expand Up @@ -82,12 +84,15 @@ public static RuntimeDelegate getInstance() {
// Local variable is used to limit the number of more expensive accesses to a volatile field.
RuntimeDelegate result = cachedDelegate;
if (result == null) { // First check (no locking)
synchronized (RD_LOCK) {
RD_LOCK.lock();
try {
result = cachedDelegate;
if (result == null) { // Second check (with locking)
result = findDelegate();
cachedDelegate = result;
}
} finally {
RD_LOCK.unlock();
}
}
return result;
Expand Down Expand Up @@ -132,8 +137,11 @@ public static void setInstance(final RuntimeDelegate rd) {
if (security != null) {
security.checkPermission(suppressAccessChecksPermission);
}
synchronized (RD_LOCK) {
RD_LOCK.lock();
try {
RuntimeDelegate.cachedDelegate = rd;
} finally {
RD_LOCK.unlock();
}
}

Expand Down

0 comments on commit cf60c62

Please sign in to comment.