Skip to content

Commit 8804cb6

Browse files
committed
Remove ReentrantLock usage in HttpRequestBuilder
Switch to a static holder class for lazily initializing the default executor to avoid needing to use an explicit lock. Also technically fixes a race condition where multiple executors could get initialized.
1 parent 30bc56b commit 8804cb6

File tree

1 file changed

+6
-20
lines changed

1 file changed

+6
-20
lines changed

spectator-ext-ipc/src/main/java/com/netflix/spectator/ipc/http/HttpRequestBuilder.java

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,6 @@
4242
import java.util.concurrent.Executors;
4343
import java.util.concurrent.ThreadFactory;
4444
import java.util.concurrent.atomic.AtomicInteger;
45-
import java.util.concurrent.locks.Lock;
46-
import java.util.concurrent.locks.ReentrantLock;
4745
import java.util.function.Consumer;
4846
import java.util.function.Supplier;
4947
import java.util.zip.Deflater;
@@ -62,12 +60,6 @@ public class HttpRequestBuilder {
6260

6361
private static final StreamHelper STREAM_HELPER = new StreamHelper();
6462

65-
private static final Lock LOCK = new ReentrantLock();
66-
67-
// Should not be used directly, use the method of the same name that will create the
68-
// executor if needed on the first access.
69-
private static volatile ExecutorService defaultExecutor;
70-
7163
private static ThreadFactory newThreadFactory() {
7264
return new ThreadFactory() {
7365
private final AtomicInteger next = new AtomicInteger();
@@ -82,18 +74,12 @@ private static ThreadFactory newThreadFactory() {
8274
}
8375

8476
private static ExecutorService defaultExecutor() {
85-
ExecutorService executor = defaultExecutor;
86-
if (executor != null) {
87-
return executor;
88-
}
89-
LOCK.lock();
90-
try {
91-
defaultExecutor = Executors.newFixedThreadPool(
92-
Runtime.getRuntime().availableProcessors(), newThreadFactory());
93-
return defaultExecutor;
94-
} finally {
95-
LOCK.unlock();
96-
}
77+
return DefaultExecutorHolder.DEFAULT_EXECUTOR;
78+
}
79+
80+
private static final class DefaultExecutorHolder {
81+
private static final ExecutorService DEFAULT_EXECUTOR = Executors.newFixedThreadPool(
82+
Runtime.getRuntime().availableProcessors(), newThreadFactory());
9783
}
9884

9985
private final URI uri;

0 commit comments

Comments
 (0)