Revise synchronized blocks

- Replace synchronized with Lock when guarding long-running operations
- Remove unnecessary synchronization in FileSystemWatcher
- Replace HashMap with ConcurrentHashMap in Restarter
- Remove unnecessary locking on AtomicBoolean in
  SpringApplicationBuilder
- Remove unnecessary locking in SimpleFormatter

Closes gh-36670
This commit is contained in:
Moritz Halbritter
2023-08-02 14:30:38 +02:00
parent 6506208d29
commit 497bbf9c2d
19 changed files with 380 additions and 150 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -158,9 +158,7 @@ public class FileSystemWatcher {
}
private void checkNotStarted() {
synchronized (this.monitor) {
Assert.state(this.watchThread == null, "FileSystemWatcher already started");
}
Assert.state(this.watchThread == null, "FileSystemWatcher already started");
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,6 +29,8 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -57,7 +59,12 @@ public class LiveReloadServer {
private final List<Connection> connections = new ArrayList<>();
private final Object monitor = new Object();
/**
* Guards access to {@link #connections}.
*/
private final Lock connectionsLock = new ReentrantLock();
private final Lock lock = new ReentrantLock();
private final int port;
@@ -108,7 +115,8 @@ public class LiveReloadServer {
* @throws IOException in case of I/O errors
*/
public int start() throws IOException {
synchronized (this.monitor) {
this.lock.lock();
try {
Assert.state(!isStarted(), "Server already started");
logger.debug(LogMessage.format("Starting live reload server on port %s", this.port));
this.serverSocket = new ServerSocket(this.port);
@@ -119,6 +127,9 @@ public class LiveReloadServer {
this.listenThread.start();
return localPort;
}
finally {
this.lock.unlock();
}
}
/**
@@ -126,9 +137,13 @@ public class LiveReloadServer {
* @return {@code true} if the server is running
*/
public boolean isStarted() {
synchronized (this.monitor) {
this.lock.lock();
try {
return this.listenThread != null;
}
finally {
this.lock.unlock();
}
}
/**
@@ -163,7 +178,8 @@ public class LiveReloadServer {
* @throws IOException in case of I/O errors
*/
public void stop() throws IOException {
synchronized (this.monitor) {
this.lock.lock();
try {
if (this.listenThread != null) {
closeAllConnections();
try {
@@ -184,22 +200,31 @@ public class LiveReloadServer {
this.serverSocket = null;
}
}
finally {
this.lock.unlock();
}
}
private void closeAllConnections() throws IOException {
synchronized (this.connections) {
this.connectionsLock.lock();
try {
for (Connection connection : this.connections) {
connection.close();
}
}
finally {
this.connectionsLock.unlock();
}
}
/**
* Trigger livereload of all connected clients.
*/
public void triggerReload() {
synchronized (this.monitor) {
synchronized (this.connections) {
this.lock.lock();
try {
this.connectionsLock.lock();
try {
for (Connection connection : this.connections) {
try {
connection.triggerReload();
@@ -209,19 +234,33 @@ public class LiveReloadServer {
}
}
}
finally {
this.connectionsLock.unlock();
}
}
finally {
this.lock.unlock();
}
}
private void addConnection(Connection connection) {
synchronized (this.connections) {
this.connectionsLock.lock();
try {
this.connections.add(connection);
}
finally {
this.connectionsLock.unlock();
}
}
private void removeConnection(Connection connection) {
synchronized (this.connections) {
this.connectionsLock.lock();
try {
this.connections.remove(connection);
}
finally {
this.connectionsLock.unlock();
}
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +22,6 @@ import java.lang.reflect.Field;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
@@ -30,6 +29,7 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
@@ -92,7 +92,7 @@ public class Restarter {
private final ClassLoaderFiles classLoaderFiles = new ClassLoaderFiles();
private final Map<String, Object> attributes = new HashMap<>();
private final Map<String, Object> attributes = new ConcurrentHashMap<>();
private final BlockingDeque<LeakSafeThread> leakSafeThreads = new LinkedBlockingDeque<>();
@@ -440,18 +440,11 @@ public class Restarter {
}
public Object getOrAddAttribute(String name, final ObjectFactory<?> objectFactory) {
synchronized (this.attributes) {
if (!this.attributes.containsKey(name)) {
this.attributes.put(name, objectFactory.getObject());
}
return this.attributes.get(name);
}
return this.attributes.computeIfAbsent(name, (ignore) -> objectFactory.getObject());
}
public Object removeAttribute(String name) {
synchronized (this.attributes) {
return this.attributes.remove(name);
}
return this.attributes.remove(name);
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,8 @@ import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -49,7 +51,7 @@ public class TunnelClient implements SmartInitializingSingleton {
private final TunnelClientListeners listeners = new TunnelClientListeners();
private final Object monitor = new Object();
private final Lock lock = new ReentrantLock();
private final int listenPort;
@@ -66,7 +68,8 @@ public class TunnelClient implements SmartInitializingSingleton {
@Override
public void afterSingletonsInstantiated() {
synchronized (this.monitor) {
this.lock.lock();
try {
if (this.serverThread == null) {
try {
start();
@@ -76,6 +79,9 @@ public class TunnelClient implements SmartInitializingSingleton {
}
}
}
finally {
this.lock.unlock();
}
}
/**
@@ -84,7 +90,8 @@ public class TunnelClient implements SmartInitializingSingleton {
* @throws IOException in case of I/O errors
*/
public int start() throws IOException {
synchronized (this.monitor) {
this.lock.lock();
try {
Assert.state(this.serverThread == null, "Server already started");
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(this.listenPort));
@@ -94,6 +101,9 @@ public class TunnelClient implements SmartInitializingSingleton {
this.serverThread.start();
return port;
}
finally {
this.lock.unlock();
}
}
/**
@@ -101,7 +111,8 @@ public class TunnelClient implements SmartInitializingSingleton {
* @throws IOException in case of I/O errors
*/
public void stop() throws IOException {
synchronized (this.monitor) {
this.lock.lock();
try {
if (this.serverThread != null) {
this.serverThread.close();
try {
@@ -113,12 +124,19 @@ public class TunnelClient implements SmartInitializingSingleton {
this.serverThread = null;
}
}
finally {
this.lock.unlock();
}
}
protected final ServerThread getServerThread() {
synchronized (this.monitor) {
this.lock.lock();
try {
return this.serverThread;
}
finally {
this.lock.unlock();
}
}
public void addListener(TunnelClientListener listener) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2019 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,8 @@ import java.io.IOException;
import java.nio.channels.WritableByteChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.springframework.util.Assert;
@@ -36,7 +38,7 @@ public class HttpTunnelPayloadForwarder {
private final Map<Long, HttpTunnelPayload> queue = new HashMap<>();
private final Object monitor = new Object();
private final Lock lock = new ReentrantLock();
private final WritableByteChannel targetChannel;
@@ -52,7 +54,8 @@ public class HttpTunnelPayloadForwarder {
}
public void forward(HttpTunnelPayload payload) throws IOException {
synchronized (this.monitor) {
this.lock.lock();
try {
long seq = payload.getSequence();
if (this.lastRequestSeq != seq - 1) {
Assert.state(this.queue.size() < MAXIMUM_QUEUE_SIZE, "Too many messages queued");
@@ -67,6 +70,9 @@ public class HttpTunnelPayloadForwarder {
forward(queuedItem);
}
}
finally {
this.lock.unlock();
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,9 @@ import java.util.Deque;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -122,7 +125,12 @@ public class HttpTunnelServer {
private long disconnectTimeout = DEFAULT_DISCONNECT_TIMEOUT;
private volatile ServerThread serverThread;
/**
* Guards access to {@link #serverThread}.
*/
private final Lock serverThreadLock = new ReentrantLock();
private ServerThread serverThread;
/**
* Creates a new {@link HttpTunnelServer} instance.
@@ -164,7 +172,8 @@ public class HttpTunnelServer {
* @throws IOException in case of I/O errors
*/
protected ServerThread getServerThread() throws IOException {
synchronized (this) {
this.serverThreadLock.lock();
try {
if (this.serverThread == null) {
ByteChannel channel = this.serverConnection.open(this.longPollTimeout);
this.serverThread = new ServerThread(channel);
@@ -172,15 +181,22 @@ public class HttpTunnelServer {
}
return this.serverThread;
}
finally {
this.serverThreadLock.unlock();
}
}
/**
* Called when the server thread exits.
*/
void clearServerThread() {
synchronized (this) {
this.serverThreadLock.lock();
try {
this.serverThread = null;
}
finally {
this.serverThreadLock.unlock();
}
}
/**
@@ -210,6 +226,13 @@ public class HttpTunnelServer {
private final Deque<HttpConnection> httpConnections;
/**
* Guards access to {@link #httpConnections}.
*/
private final Lock httpConnectionsLock = new ReentrantLock();
private final Condition httpConnectionsCondition = this.httpConnectionsLock.newCondition();
private final HttpTunnelPayloadForwarder payloadForwarder;
private boolean closed;
@@ -247,7 +270,8 @@ public class HttpTunnelServer {
while (this.targetServer.isOpen()) {
closeStaleHttpConnections();
ByteBuffer data = HttpTunnelPayload.getPayloadData(this.targetServer);
synchronized (this.httpConnections) {
this.httpConnectionsLock.lock();
try {
if (data != null) {
HttpTunnelPayload payload = new HttpTunnelPayload(this.responseSeq.incrementAndGet(), data);
payload.logIncoming();
@@ -255,15 +279,20 @@ public class HttpTunnelServer {
connection.respond(payload);
}
}
finally {
this.httpConnectionsLock.unlock();
}
}
}
private HttpConnection getOrWaitForHttpConnection() {
synchronized (this.httpConnections) {
this.httpConnectionsLock.lock();
try {
HttpConnection httpConnection = this.httpConnections.pollFirst();
while (httpConnection == null) {
try {
this.httpConnections.wait(HttpTunnelServer.this.longPollTimeout);
this.httpConnectionsCondition.await(HttpTunnelServer.this.longPollTimeout,
TimeUnit.MILLISECONDS);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
@@ -273,10 +302,14 @@ public class HttpTunnelServer {
}
return httpConnection;
}
finally {
this.httpConnectionsLock.unlock();
}
}
private void closeStaleHttpConnections() throws IOException {
synchronized (this.httpConnections) {
this.httpConnectionsLock.lock();
try {
checkNotDisconnected();
Iterator<HttpConnection> iterator = this.httpConnections.iterator();
while (iterator.hasNext()) {
@@ -287,6 +320,9 @@ public class HttpTunnelServer {
}
}
}
finally {
this.httpConnectionsLock.unlock();
}
}
private void checkNotDisconnected() {
@@ -298,7 +334,8 @@ public class HttpTunnelServer {
}
private void closeHttpConnections() {
synchronized (this.httpConnections) {
this.httpConnectionsLock.lock();
try {
while (!this.httpConnections.isEmpty()) {
try {
this.httpConnections.removeFirst().respond(HttpStatus.GONE);
@@ -308,6 +345,9 @@ public class HttpTunnelServer {
}
}
}
finally {
this.httpConnectionsLock.unlock();
}
}
private void closeTargetServer() {
@@ -328,13 +368,17 @@ public class HttpTunnelServer {
if (this.closed) {
httpConnection.respond(HttpStatus.GONE);
}
synchronized (this.httpConnections) {
this.httpConnectionsLock.lock();
try {
while (this.httpConnections.size() > 1) {
this.httpConnections.removeFirst().respond(HttpStatus.TOO_MANY_REQUESTS);
}
this.lastHttpRequestTime = System.currentTimeMillis();
this.httpConnections.addLast(httpConnection);
this.httpConnections.notify();
this.httpConnectionsCondition.signal();
}
finally {
this.httpConnectionsLock.unlock();
}
forwardToTargetServer(httpConnection);
}
@@ -368,6 +412,10 @@ public class HttpTunnelServer {
private volatile boolean complete = false;
private final Lock lock = new ReentrantLock();
private final Condition lockCondition = this.lock.newCondition();
public HttpConnection(ServerHttpRequest request, ServerHttpResponse response) {
this.createTime = System.currentTimeMillis();
this.request = request;
@@ -426,8 +474,12 @@ public class HttpTunnelServer {
if (this.async == null) {
while (!this.complete) {
try {
synchronized (this) {
wait(1000);
this.lock.lock();
try {
this.lockCondition.await(1, TimeUnit.SECONDS);
}
finally {
this.lock.unlock();
}
}
catch (InterruptedException ex) {
@@ -476,9 +528,13 @@ public class HttpTunnelServer {
this.async.complete();
}
else {
synchronized (this) {
this.lock.lock();
try {
this.complete = true;
notifyAll();
this.lockCondition.signalAll();
}
finally {
this.lock.unlock();
}
}
}