Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: Using ReentrantLock instead of synchronized #1299

Merged
merged 1 commit into from
Jan 1, 2025
Merged
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
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
Loading