Skip to content

Commit 3e8d957

Browse files
committed
Performance: Using ReentrantLock instead of synchronized
1 parent 49b0765 commit 3e8d957

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

jaxrs-api/src/main/java/jakarta/ws/rs/ext/RuntimeDelegate.java

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
import java.lang.reflect.ReflectPermission;
2020
import java.net.URL;
2121
import java.util.concurrent.CompletionStage;
22+
import java.util.concurrent.locks.Lock;
23+
import java.util.concurrent.locks.ReentrantLock;
2224

2325
import jakarta.ws.rs.SeBootstrap;
2426
import jakarta.ws.rs.SeBootstrap.Instance;
@@ -45,7 +47,7 @@ public abstract class RuntimeDelegate {
4547
* {@link RuntimeDelegate#getInstance()}.
4648
*/
4749
public static final String JAXRS_RUNTIME_DELEGATE_PROPERTY = "jakarta.ws.rs.ext.RuntimeDelegate";
48-
private static final Object RD_LOCK = new Object();
50+
private static final Lock RD_LOCK = new ReentrantLock();
4951
private static ReflectPermission suppressAccessChecksPermission = new ReflectPermission("suppressAccessChecks");
5052
private static volatile RuntimeDelegate cachedDelegate;
5153

@@ -82,12 +84,15 @@ public static RuntimeDelegate getInstance() {
8284
// Local variable is used to limit the number of more expensive accesses to a volatile field.
8385
RuntimeDelegate result = cachedDelegate;
8486
if (result == null) { // First check (no locking)
85-
synchronized (RD_LOCK) {
87+
RD_LOCK.lock();
88+
try {
8689
result = cachedDelegate;
8790
if (result == null) { // Second check (with locking)
8891
result = findDelegate();
8992
cachedDelegate = result;
9093
}
94+
} finally {
95+
RD_LOCK.unlock();
9196
}
9297
}
9398
return result;
@@ -132,8 +137,11 @@ public static void setInstance(final RuntimeDelegate rd) {
132137
if (security != null) {
133138
security.checkPermission(suppressAccessChecksPermission);
134139
}
135-
synchronized (RD_LOCK) {
140+
RD_LOCK.lock();
141+
try {
136142
RuntimeDelegate.cachedDelegate = rd;
143+
} finally {
144+
RD_LOCK.unlock();
137145
}
138146
}
139147

0 commit comments

Comments
 (0)