From 8d69fc41a7f8c26fcd90fc0f7300f81eaede06be Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Mon, 27 Jul 2020 23:14:05 +0200 Subject: [PATCH 1/3] Fixes #5083 - Convert synchronized usages to AutoLock. * Replaced relevant usages of synchronized with AutoLock. * Made AutoLock serializable since classes that use it may be stored in the HttpSession. * Added convenience methods to AutoLock to execute lambdas with the lock held. * Introduced AutoLock.WithCondition to use a Lock and a Condition together. Signed-off-by: Simone Bordet --- .../annotations/AnnotationIntrospector.java | 16 +- .../org/eclipse/jetty/client/HttpChannel.java | 11 +- .../eclipse/jetty/client/HttpConnection.java | 8 +- .../eclipse/jetty/client/HttpExchange.java | 41 +- .../eclipse/jetty/client/HttpReceiver.java | 11 +- .../jetty/client/MultiplexConnectionPool.java | 40 +- .../client/RoundRobinConnectionPool.java | 30 +- .../client/util/AsyncRequestContent.java | 20 +- .../jetty/deploy/DeploymentManager.java | 2 +- .../client/http/HttpConnectionOverFCGI.java | 9 +- .../eclipse/jetty/fcgi/generator/Flusher.java | 12 +- .../org/eclipse/jetty/http/MimeTypes.java | 2 +- .../jetty/http2/client/RawHTTP2ProxyTest.java | 34 +- .../eclipse/jetty/http2/HTTP2Connection.java | 12 +- .../org/eclipse/jetty/http2/HTTP2Flusher.java | 24 +- .../org/eclipse/jetty/http2/HTTP2Session.java | 16 +- .../org/eclipse/jetty/http2/HTTP2Stream.java | 41 +- .../jetty/http2/HTTP2StreamEndPoint.java | 25 +- .../client/http/HttpReceiverOverHTTP2.java | 17 +- .../http2/server/HTTP2ServerConnection.java | 20 +- .../http2/server/HttpTransportOverHTTP2.java | 18 +- .../eclipse/jetty/io/ByteArrayEndPoint.java | 24 +- .../org/eclipse/jetty/io/ManagedSelector.java | 19 +- .../jetty/io/SocketChannelEndPoint.java | 8 +- .../eclipse/jetty/io/WriterOutputStream.java | 7 +- .../eclipse/jetty/io/ssl/SslConnection.java | 33 +- .../eclipse/jetty/io/SslConnectionTest.java | 2 +- .../org/eclipse/jetty/jaas/spi/UserInfo.java | 11 +- .../eclipse/jetty/jndi/ContextFactory.java | 42 +- .../osgi/boot/utils/OSGiClassLoader.java | 47 +- .../authentication/DigestAuthenticator.java | 4 +- .../jetty/server/AbstractConnector.java | 22 +- .../eclipse/jetty/server/AcceptRateLimit.java | 19 +- .../jetty/server/AsyncRequestLogWriter.java | 2 +- .../eclipse/jetty/server/ConnectionLimit.java | 31 +- .../jetty/server/CustomRequestLog.java | 2 +- .../jetty/server/HttpChannelState.java | 165 ++--- .../org/eclipse/jetty/server/HttpInput.java | 61 +- .../org/eclipse/jetty/server/HttpOutput.java | 56 +- .../server/MultiPartFormInputStream.java | 41 +- .../jetty/server/RequestLogWriter.java | 36 +- .../eclipse/jetty/server/ResourceService.java | 25 +- .../eclipse/jetty/server/ShutdownMonitor.java | 65 +- .../jetty/server/Slf4jRequestLogWriter.java | 2 +- .../jetty/server/handler/ContextHandler.java | 187 +++--- .../session/DefaultSessionIdManager.java | 10 +- .../jetty/server/session/HouseKeeper.java | 10 +- .../eclipse/jetty/server/session/Session.java | 105 ++-- .../jetty/server/session/SessionHandler.java | 1 + .../server/ServerConnectorTimeoutTest.java | 2 +- .../org/eclipse/jetty/servlet/BaseHolder.java | 47 +- .../eclipse/jetty/servlet/FilterHolder.java | 22 +- .../org/eclipse/jetty/servlet/Holder.java | 12 +- .../org/eclipse/jetty/servlet/Invoker.java | 5 +- .../eclipse/jetty/servlet/ListenerHolder.java | 19 +- .../eclipse/jetty/servlet/ServletHandler.java | 383 ++++++------ .../eclipse/jetty/servlet/ServletHolder.java | 71 ++- .../org/eclipse/jetty/servlets/DoSFilter.java | 6 +- .../jetty/servlets/EventSourceServlet.java | 20 +- .../jetty/util/ajax/JSONDateConvertor.java | 4 +- .../jetty/util/RolloverFileOutputStream.java | 46 +- .../java/org/eclipse/jetty/util/Scanner.java | 317 +++++----- .../org/eclipse/jetty/util/StringUtil.java | 13 +- .../java/org/eclipse/jetty/util/URIUtil.java | 31 +- .../org/eclipse/jetty/util/UrlEncoded.java | 565 +++++++++--------- .../util/component/AbstractLifeCycle.java | 7 +- .../util/component/AttributeContainerMap.java | 41 +- .../jetty/util/resource/JarFileResource.java | 157 ++--- .../jetty/util/resource/JarResource.java | 38 +- .../jetty/util/resource/URLResource.java | 97 +-- .../jetty/util/security/Credential.java | 36 +- .../jetty/util/ssl/SslContextFactory.java | 17 +- .../jetty/util/statistic/RateStatistic.java | 27 +- .../eclipse/jetty/util/thread/AutoLock.java | 124 +++- .../jetty/util/thread/QueuedThreadPool.java | 10 +- .../jetty/util/thread/ShutdownThread.java | 60 +- .../util/thread/strategy/EatWhatYouKill.java | 24 +- .../eclipse/jetty/webapp/Configurations.java | 84 +-- .../org/eclipse/jetty/webapp/MetaData.java | 49 +- .../jetty/webapp/ConfigurationsTest.java | 4 +- .../jetty/webapp/WebAppContextTest.java | 8 +- .../websocket/core/internal/FrameFlusher.java | 21 +- .../core/internal/FrameSequence.java | 4 +- .../core/internal/TransformingFlusher.java | 15 +- .../core/internal/WebSocketConnection.java | 25 +- .../core/internal/WebSocketSessionState.java | 28 +- .../common/JavaxWebSocketFrameHandler.java | 41 +- .../javax/common/JavaxWebSocketSession.java | 2 +- .../websocket/client/WebSocketClient.java | 2 +- .../common/JettyWebSocketFrameHandler.java | 17 +- .../util/messages/MessageInputStream.java | 13 +- .../util/messages/MessageOutputStream.java | 27 +- .../eclipse/jetty/xml/XmlConfiguration.java | 3 +- .../java/org/eclipse/jetty/xml/XmlParser.java | 91 ++- .../jetty/http/tools/HttpTesterTest.java | 2 +- .../util/jmh/DateCacheSimpleDateFormat.java | 35 +- .../main/java/com/acme/DispatchServlet.java | 5 - .../src/main/java/com/acme/Dump.java | 2 +- .../src/main/java/com/acme/RegTest.java | 5 - 99 files changed, 2014 insertions(+), 2116 deletions(-) diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java index 4ffe33c9cc2d..aed655445f3c 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java @@ -28,6 +28,7 @@ import org.eclipse.jetty.servlet.BaseHolder; import org.eclipse.jetty.servlet.Source.Origin; import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.webapp.WebDescriptor; import org.slf4j.Logger; @@ -41,6 +42,8 @@ public class AnnotationIntrospector { private static final Logger LOG = LoggerFactory.getLogger(AnnotationIntrospector.class); + + private final AutoLock _lock = new AutoLock(); private final Set> _introspectedClasses = new HashSet<>(); private final List _handlers = new ArrayList(); private final WebAppContext _context; @@ -195,14 +198,13 @@ public void introspect(Object o, Object metaInfo) Class clazz = o.getClass(); - synchronized (_introspectedClasses) + try (AutoLock ignored = _lock.lock()) { - //Synchronize on the set of already introspected classes. - //This ensures that only 1 thread can be introspecting, and that - //thread must have fully finished generating the products of - //introspection before another thread is allowed in. - //We remember the classes that we have introspected to avoid - //reprocessing the same class. + // Lock to ensure that only 1 thread can be introspecting, and that + // thread must have fully finished generating the products of + // the introspection before another thread is allowed in. + // We remember the classes that we have introspected to avoid + // reprocessing the same class. if (_introspectedClasses.add(clazz)) { for (IntrospectableAnnotationHandler handler : _handlers) diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java index ef62918a6916..7f1519a3270a 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java @@ -19,6 +19,7 @@ package org.eclipse.jetty.client; import org.eclipse.jetty.client.api.Result; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,6 +27,7 @@ public abstract class HttpChannel { private static final Logger LOG = LoggerFactory.getLogger(HttpChannel.class); + private final AutoLock _lock = new AutoLock(); private final HttpDestination _destination; private final TimeoutCompleteListener _totalTimeout; private HttpExchange _exchange; @@ -58,7 +60,7 @@ public boolean associate(HttpExchange exchange) { boolean result = false; boolean abort = true; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_exchange == null) { @@ -85,7 +87,7 @@ public boolean associate(HttpExchange exchange) public boolean disassociate(HttpExchange exchange) { boolean result = false; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { HttpExchange existing = _exchange; _exchange = null; @@ -103,10 +105,7 @@ public boolean disassociate(HttpExchange exchange) public HttpExchange getHttpExchange() { - synchronized (this) - { - return _exchange; - } + return _lock.runLocked(() -> _exchange); } protected abstract HttpSender getHttpSender(); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java index 39fde1c7e085..f3c0e136d293 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java @@ -36,6 +36,7 @@ import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.util.HttpCookieStore; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +44,7 @@ public abstract class HttpConnection implements IConnection { private static final Logger LOG = LoggerFactory.getLogger(HttpConnection.class); + private final AutoLock lock = new AutoLock(); private final HttpDestination destination; private int idleTimeoutGuard; private long idleTimeoutStamp; @@ -87,7 +89,7 @@ protected SendFailure send(HttpChannel channel, HttpExchange exchange) // the request is associated to the channel and sent. // Use a counter to support multiplexed requests. boolean send; - synchronized (this) + try (AutoLock ignored = lock.lock()) { send = idleTimeoutGuard >= 0; if (send) @@ -111,7 +113,7 @@ protected SendFailure send(HttpChannel channel, HttpExchange exchange) result = new SendFailure(new HttpRequestException("Could not associate request to connection", request), false); } - synchronized (this) + try (AutoLock ignored = lock.lock()) { --idleTimeoutGuard; idleTimeoutStamp = System.nanoTime(); @@ -250,7 +252,7 @@ private void applyRequestAuthentication(Request request) public boolean onIdleTimeout(long idleTimeout) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (idleTimeoutGuard == 0) { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java index 75a89dcefe49..01b81fcc2dbd 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java @@ -23,6 +23,7 @@ import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,6 +31,7 @@ public class HttpExchange { private static final Logger LOG = LoggerFactory.getLogger(HttpExchange.class); + private final AutoLock lock = new AutoLock(); private final HttpDestination destination; private final HttpRequest request; private final List listeners; @@ -68,10 +70,7 @@ public HttpRequest getRequest() public Throwable getRequestFailure() { - synchronized (this) - { - return requestFailure; - } + return lock.runLocked(() -> requestFailure); } public List getResponseListeners() @@ -86,10 +85,7 @@ public HttpResponse getResponse() public Throwable getResponseFailure() { - synchronized (this) - { - return responseFailure; - } + return lock.runLocked(() -> responseFailure); } /** @@ -103,7 +99,7 @@ boolean associate(HttpChannel channel) { boolean result = false; boolean abort = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { // Only associate if the exchange state is initial, // as the exchange could be already failed. @@ -127,7 +123,7 @@ boolean associate(HttpChannel channel) void disassociate(HttpChannel channel) { boolean abort = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (_channel != channel || requestState != State.TERMINATED || responseState != State.TERMINATED) abort = true; @@ -140,18 +136,12 @@ void disassociate(HttpChannel channel) private HttpChannel getHttpChannel() { - synchronized (this) - { - return _channel; - } + return lock.runLocked(() -> _channel); } public boolean requestComplete(Throwable failure) { - synchronized (this) - { - return completeRequest(failure); - } + return lock.runLocked(() -> completeRequest(failure)); } private boolean completeRequest(Throwable failure) @@ -167,10 +157,7 @@ private boolean completeRequest(Throwable failure) public boolean responseComplete(Throwable failure) { - synchronized (this) - { - return completeResponse(failure); - } + return lock.runLocked(() -> completeResponse(failure)); } private boolean completeResponse(Throwable failure) @@ -187,7 +174,7 @@ private boolean completeResponse(Throwable failure) public Result terminateRequest() { Result result = null; - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (requestState == State.COMPLETED) requestState = State.TERMINATED; @@ -204,7 +191,7 @@ public Result terminateRequest() public Result terminateResponse() { Result result = null; - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (responseState == State.COMPLETED) responseState = State.TERMINATED; @@ -224,7 +211,7 @@ public boolean abort(Throwable failure) // This will avoid that this exchange can be associated to a channel. boolean abortRequest; boolean abortResponse; - synchronized (this) + try (AutoLock ignored = lock.lock()) { abortRequest = completeRequest(failure); abortResponse = completeResponse(failure); @@ -283,7 +270,7 @@ private void notifyFailureComplete(Throwable failure) public void resetResponse() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { responseState = State.PENDING; responseFailure = null; @@ -300,7 +287,7 @@ public void proceed(Throwable failure) @Override public String toString() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { return String.format("%s@%x req=%s/%s@%h res=%s/%s@%h", HttpExchange.class.getSimpleName(), diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java index 59322a3f44ec..6325c01864c5 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java @@ -42,6 +42,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.MathUtils; import org.eclipse.jetty.util.component.Destroyable; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,6 +75,7 @@ public abstract class HttpReceiver { private static final Logger LOG = LoggerFactory.getLogger(HttpReceiver.class); + private final AutoLock lock = new AutoLock(); private final AtomicReference responseState = new AtomicReference<>(ResponseState.IDLE); private final HttpChannel channel; private ContentListeners contentListeners; @@ -98,7 +100,7 @@ void demand(long n) throw new IllegalArgumentException("Invalid demand " + n); boolean resume = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { demand = MathUtils.cappedAdd(demand, n); if (stalled) @@ -126,15 +128,12 @@ protected long demand() private long demand(LongUnaryOperator operator) { - synchronized (this) - { - return demand = operator.applyAsLong(demand); - } + return lock.runLocked(() -> demand = operator.applyAsLong(demand)); } protected boolean hasDemandOrStall() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { stalled = demand <= 0; return !stalled; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java index 3af05ee8e191..d2034866470b 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java @@ -32,6 +32,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.component.DumpableCollection; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Sweeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,6 +41,7 @@ public class MultiplexConnectionPool extends AbstractConnectionPool implements C { private static final Logger LOG = LoggerFactory.getLogger(MultiplexConnectionPool.class); + private final AutoLock lock = new AutoLock(); private final Deque idleConnections; private final Map activeConnections; private int maxMultiplex; @@ -80,19 +82,13 @@ private static int ceilDiv(int a, int b) @Override public int getMaxMultiplex() { - synchronized (this) - { - return maxMultiplex; - } + return lock.runLocked(() -> maxMultiplex); } @Override public void setMaxMultiplex(int maxMultiplex) { - synchronized (this) - { - this.maxMultiplex = maxMultiplex; - } + lock.runLocked(() -> this.maxMultiplex = maxMultiplex); } @Override @@ -103,7 +99,7 @@ public boolean accept(Connection connection) LOG.debug("Accepted {} {}", accepted, connection); if (accepted) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { Holder holder = new Holder(connection); activeConnections.put(connection, holder); @@ -117,20 +113,14 @@ public boolean accept(Connection connection) @Override public boolean isActive(Connection connection) { - synchronized (this) - { - return activeConnections.containsKey(connection); - } + return lock.runLocked(() -> activeConnections.containsKey(connection)); } @Override protected void onCreated(Connection connection) { - synchronized (this) - { - // Use "cold" connections as last. - idleConnections.offer(new Holder(connection)); - } + // Use "cold" connections as last. + lock.runLocked(() -> idleConnections.offer(new Holder(connection))); idle(connection, false); } @@ -138,7 +128,7 @@ protected void onCreated(Connection connection) protected Connection activate() { Holder result = null; - synchronized (this) + try (AutoLock ignored = lock.lock()) { for (Holder holder : activeConnections.values()) { @@ -169,7 +159,7 @@ public boolean release(Connection connection) boolean closed = isClosed(); boolean idle = false; Holder holder; - synchronized (this) + try (AutoLock ignored = lock.lock()) { holder = activeConnections.get(connection); if (holder != null) @@ -205,7 +195,7 @@ protected boolean remove(Connection connection, boolean force) { boolean activeRemoved = true; boolean idleRemoved = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { Holder holder = activeConnections.remove(connection); if (holder == null) @@ -236,7 +226,7 @@ public void close() { super.close(); List connections; - synchronized (this) + try (AutoLock ignored = lock.lock()) { connections = idleConnections.stream().map(holder -> holder.connection).collect(Collectors.toList()); connections.addAll(activeConnections.keySet()); @@ -249,7 +239,7 @@ public void dump(Appendable out, String indent) throws IOException { DumpableCollection active; DumpableCollection idle; - synchronized (this) + try (AutoLock ignored = lock.lock()) { active = new DumpableCollection("active", new ArrayList<>(activeConnections.values())); idle = new DumpableCollection("idle", new ArrayList<>(idleConnections)); @@ -261,7 +251,7 @@ public void dump(Appendable out, String indent) throws IOException public boolean sweep() { List toSweep = new ArrayList<>(); - synchronized (this) + try (AutoLock ignored = lock.lock()) { activeConnections.values().stream() .map(holder -> holder.connection) @@ -289,7 +279,7 @@ public String toString() { int activeSize; int idleSize; - synchronized (this) + try (AutoLock ignored = lock.lock()) { activeSize = activeConnections.size(); idleSize = idleConnections.size(); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java index e13fba9390dd..c45bad9115cf 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java @@ -26,10 +26,12 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.Dumpable; +import org.eclipse.jetty.util.thread.AutoLock; @ManagedObject public class RoundRobinConnectionPool extends AbstractConnectionPool implements ConnectionPool.Multiplexable { + private final AutoLock lock = new AutoLock(); private final List entries; private int maxMultiplex; private int index; @@ -53,19 +55,13 @@ public RoundRobinConnectionPool(HttpDestination destination, int maxConnections, @Override public int getMaxMultiplex() { - synchronized (this) - { - return maxMultiplex; - } + return lock.runLocked(() -> maxMultiplex); } @Override public void setMaxMultiplex(int maxMultiplex) { - synchronized (this) - { - this.maxMultiplex = maxMultiplex; - } + lock.runLocked(() -> this.maxMultiplex = maxMultiplex); } /** @@ -86,7 +82,7 @@ public Connection acquire(boolean create) @Override protected void onCreated(Connection connection) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { for (Entry entry : entries) { @@ -104,7 +100,7 @@ protected void onCreated(Connection connection) protected Connection activate() { Connection connection = null; - synchronized (this) + try (AutoLock ignored = lock.lock()) { int offset = 0; int capacity = getMaxConnectionCount(); @@ -139,7 +135,7 @@ protected Connection activate() @Override public boolean isActive(Connection connection) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { for (Entry entry : entries) { @@ -155,7 +151,7 @@ public boolean release(Connection connection) { boolean found = false; boolean idle = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { for (Entry entry : entries) { @@ -180,7 +176,7 @@ public boolean release(Connection connection) public boolean remove(Connection connection) { boolean found = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { for (Entry entry : entries) { @@ -203,11 +199,7 @@ public boolean remove(Connection connection) @Override public void dump(Appendable out, String indent) throws IOException { - List connections; - synchronized (this) - { - connections = new ArrayList<>(entries); - } + List connections = lock.runLocked(() -> new ArrayList<>(entries)); Dumpable.dumpObjects(out, indent, out, connections); } @@ -216,7 +208,7 @@ public String toString() { int present = 0; int active = 0; - synchronized (this) + try (AutoLock ignored = lock.lock()) { for (Entry entry : entries) { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/AsyncRequestContent.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/AsyncRequestContent.java index 2e084786d0ca..79ac545212e3 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/AsyncRequestContent.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/AsyncRequestContent.java @@ -27,7 +27,6 @@ import java.util.Deque; import java.util.List; import java.util.Objects; -import java.util.concurrent.locks.Condition; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -42,8 +41,7 @@ public class AsyncRequestContent implements Request.Content, Request.Content.Sub { private static final Logger LOG = LoggerFactory.getLogger(AsyncRequestContent.class); - private final AutoLock lock = new AutoLock(); - private final Condition flush = lock.newCondition(); + private final AutoLock.WithCondition lock = new AutoLock.WithCondition(); private final Deque chunks = new ArrayDeque<>(); private final String contentType; private long length = -1; @@ -118,7 +116,7 @@ public void demand() public void fail(Throwable failure) { List toFail = List.of(); - try (AutoLock ignored = lock.lock()) + try (AutoLock.WithCondition l = lock.lock()) { if (this.failure == null) { @@ -128,7 +126,7 @@ public void fail(Throwable failure) .map(chunk -> chunk.callback) .collect(Collectors.toList()); chunks.clear(); - flush.signal(); + l.signal(); } } toFail.forEach(c -> c.failed(failure)); @@ -293,15 +291,15 @@ private void notifyFailure(Consumer consumer, Throwable failure) private void notifyFlush() { - try (AutoLock ignored = lock.lock()) + try (AutoLock.WithCondition l = lock.lock()) { - flush.signal(); + l.signal(); } } public void flush() throws IOException { - try (AutoLock ignored = lock.lock()) + try (AutoLock.WithCondition l = lock.lock()) { try { @@ -313,7 +311,7 @@ public void flush() throws IOException throw new IOException(failure); if (chunks.isEmpty()) return; - flush.await(); + l.await(); } } catch (InterruptedException x) @@ -327,7 +325,7 @@ public void flush() throws IOException public void close() { boolean produce = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock.WithCondition l = lock.lock()) { if (closed) return; @@ -340,7 +338,7 @@ public void close() produce = true; } } - flush.signal(); + l.signal(); } if (produce) produce(); diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java index 3793d99f7b66..b8565032e874 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java @@ -562,7 +562,7 @@ public void requestAppGoal(@Name("appId") String appId, @Name("nodeName") String requestAppGoal(appentry, nodeName); } - private synchronized void addOnStartupError(Throwable cause) + private void addOnStartupError(Throwable cause) { if (onStartupErrors == null) { diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java index 16badda409a3..9a5d950c28a1 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java @@ -54,6 +54,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,6 +62,7 @@ public class HttpConnectionOverFCGI extends AbstractConnection implements IConne { private static final Logger LOG = LoggerFactory.getLogger(HttpConnectionOverFCGI.class); + private final AutoLock lock = new AutoLock(); private final LinkedList requests = new LinkedList<>(); private final Map activeChannels = new ConcurrentHashMap<>(); private final Queue idleChannels = new ConcurrentLinkedQueue<>(); @@ -307,7 +309,7 @@ private void failAndClose(Throwable failure) private int acquireRequest() { - synchronized (requests) + try (AutoLock ignored = lock.lock()) { int last = requests.getLast(); int request = last + 1; @@ -318,10 +320,7 @@ private int acquireRequest() private void releaseRequest(int request) { - synchronized (requests) - { - requests.removeFirstOccurrence(request); - } + lock.runLocked(() -> requests.removeFirstOccurrence(request)); } protected HttpChannelOverFCGI acquireHttpChannel(int id, Request request) diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java index 0b31c501a4ae..66283bc28e13 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java @@ -24,6 +24,7 @@ import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.util.IteratingCallback; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,6 +32,7 @@ public class Flusher { private static final Logger LOG = LoggerFactory.getLogger(Flusher.class); + private final AutoLock lock = new AutoLock(); private final Queue queue = new ArrayDeque<>(); private final IteratingCallback flushCallback = new FlushCallback(); private final EndPoint endPoint; @@ -51,18 +53,12 @@ public void flush(Generator.Result... results) private void offer(Generator.Result result) { - synchronized (this) - { - queue.offer(result); - } + lock.runLocked(() -> queue.offer(result)); } private Generator.Result poll() { - synchronized (this) - { - return queue.poll(); - } + return lock.runLocked(queue::poll); } public void shutdown() diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java b/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java index f377b566cfb9..2eb61902cd19 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/MimeTypes.java @@ -291,7 +291,7 @@ public MimeTypes() { } - public synchronized Map getMimeMap() + public Map getMimeMap() { return _mimeMap; } diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java index 3ebfc00e5571..58a7484189ca 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java @@ -53,6 +53,7 @@ import org.eclipse.jetty.util.FuturePromise; import org.eclipse.jetty.util.IteratingCallback; import org.eclipse.jetty.util.Promise; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -316,7 +317,7 @@ public void onFailure(Session session, Throwable failure) private static class ClientToProxyToServer extends IteratingCallback implements Stream.Listener { - private final Object lock = this; + private final AutoLock lock = new AutoLock(); private final Map> frames = new HashMap<>(); private final Map streams = new HashMap<>(); private final ServerToProxyToClient serverToProxyToClient = new ServerToProxyToClient(); @@ -339,7 +340,7 @@ private void offer(Stream stream, Frame frame, Callback callback) if (LOGGER.isDebugEnabled()) LOGGER.debug("CPS queueing {} for {} on {}", frame, stream, stream.getSession()); boolean connected; - synchronized (lock) + try (AutoLock ignored = lock.lock()) { Deque deque = frames.computeIfAbsent(stream, s -> new ArrayDeque<>()); deque.offer(new FrameInfo(frame, callback)); @@ -363,10 +364,7 @@ public void succeeded(Session result) { if (LOGGER.isDebugEnabled()) LOGGER.debug("CPS connected to {} with {}", address, result); - synchronized (lock) - { - proxyToServerSession = result; - } + lock.runLocked(() -> proxyToServerSession = result); iterate(); } @@ -385,7 +383,7 @@ protected Action process() throws Throwable { Stream proxyToServerStream = null; Session proxyToServerSession = null; - synchronized (lock) + try (AutoLock ignored = lock.lock()) { for (Map.Entry> entry : frames.entrySet()) { @@ -415,12 +413,9 @@ protected Action process() throws Throwable @Override public void succeeded(Stream result) { - synchronized (lock) - { - if (LOGGER.isDebugEnabled()) - LOGGER.debug("CPS created {}", result); - streams.put(clientToProxyStream, result); - } + if (LOGGER.isDebugEnabled()) + LOGGER.debug("CPS created {}", result); + lock.runLocked(() -> streams.put(clientToProxyStream, result)); serverToProxyToClient.link(result, clientToProxyStream); ClientToProxyToServer.this.succeeded(); } @@ -549,17 +544,17 @@ public void onFailure(Session session, Throwable failure) private static class ServerToProxyToClient extends IteratingCallback implements Stream.Listener { - private final Object lock = this; + private final AutoLock lock = new AutoLock(); private final Map> frames = new HashMap<>(); private final Map streams = new HashMap<>(); private FrameInfo frameInfo; private Stream serverToProxyStream; @Override - protected Action process() throws Throwable + protected Action process() { Stream proxyToClientStream = null; - synchronized (lock) + try (AutoLock ignored = lock.lock()) { for (Map.Entry> entry : frames.entrySet()) { @@ -630,7 +625,7 @@ private void offer(Stream stream, Frame frame, Callback callback) { if (LOGGER.isDebugEnabled()) LOGGER.debug("SPC queueing {} for {} on {}", frame, stream, stream.getSession()); - synchronized (lock) + try (AutoLock ignored = lock.lock()) { Deque deque = frames.computeIfAbsent(stream, s -> new ArrayDeque<>()); deque.offer(new FrameInfo(frame, callback)); @@ -682,10 +677,7 @@ public boolean onIdleTimeout(Stream stream, Throwable x) private void link(Stream proxyToServerStream, Stream clientToProxyStream) { - synchronized (lock) - { - streams.put(proxyToServerStream, clientToProxyStream); - } + lock.runLocked(() -> streams.put(proxyToServerStream, clientToProxyStream)); iterate(); } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java index 206b869e58ef..b0cdbbf5a50a 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java @@ -36,6 +36,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.component.LifeCycle; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.ExecutionStrategy; import org.eclipse.jetty.util.thread.TryExecutor; import org.eclipse.jetty.util.thread.strategy.EatWhatYouKill; @@ -49,6 +50,7 @@ public class HTTP2Connection extends AbstractConnection implements WriteFlusher. // TODO remove this once we are sure EWYK is OK for http2 private static final boolean PEC_MODE = Boolean.getBoolean("org.eclipse.jetty.http2.PEC_MODE"); + private final AutoLock lock = new AutoLock(); private final Queue tasks = new ArrayDeque<>(); private final HTTP2Producer producer = new HTTP2Producer(); private final AtomicLong bytesIn = new AtomicLong(); @@ -190,10 +192,7 @@ protected void offerTask(Runnable task, boolean dispatch) private void offerTask(Runnable task) { - synchronized (this) - { - tasks.offer(task); - } + lock.runLocked(() -> tasks.offer(task)); } protected void produce() @@ -220,10 +219,7 @@ public void close() private Runnable pollTask() { - synchronized (this) - { - return tasks.poll(); - } + return lock.runLocked(tasks::poll); } @Override diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java index 93ffc90c3ac9..b87e5f711e06 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java @@ -38,6 +38,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.IteratingCallback; import org.eclipse.jetty.util.component.Dumpable; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,6 +47,7 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable private static final Logger LOG = LoggerFactory.getLogger(HTTP2Flusher.class); private static final ByteBuffer[] EMPTY_BYTE_BUFFERS = new ByteBuffer[0]; + private final AutoLock lock = new AutoLock(); private final Queue windows = new ArrayDeque<>(); private final Deque entries = new ArrayDeque<>(); private final Queue pendingEntries = new ArrayDeque<>(); @@ -64,7 +66,7 @@ public HTTP2Flusher(HTTP2Session session) public void window(IStream stream, WindowUpdateFrame frame) { Throwable closed; - synchronized (this) + try (AutoLock ignored = lock.lock()) { closed = terminated; if (closed == null) @@ -78,7 +80,7 @@ public void window(IStream stream, WindowUpdateFrame frame) public boolean prepend(Entry entry) { Throwable closed; - synchronized (this) + try (AutoLock ignored = lock.lock()) { closed = terminated; if (closed == null) @@ -97,7 +99,7 @@ public boolean prepend(Entry entry) public boolean append(Entry entry) { Throwable closed; - synchronized (this) + try (AutoLock ignored = lock.lock()) { closed = terminated; if (closed == null) @@ -115,18 +117,12 @@ public boolean append(Entry entry) private int getWindowQueueSize() { - synchronized (this) - { - return windows.size(); - } + return lock.runLocked(windows::size); } public int getFrameQueueSize() { - synchronized (this) - { - return entries.size(); - } + return lock.runLocked(entries::size); } @Override @@ -135,7 +131,7 @@ protected Action process() throws Throwable if (LOG.isDebugEnabled()) LOG.debug("Flushing {}", session); - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (terminated != null) throw terminated; @@ -323,7 +319,7 @@ protected void onCompleteFailure(Throwable x) Throwable closed; Set allEntries; - synchronized (this) + try (AutoLock ignored = lock.lock()) { closed = terminated; terminated = x; @@ -352,7 +348,7 @@ protected void onCompleteFailure(Throwable x) void terminate(Throwable cause) { Throwable closed; - synchronized (this) + try (AutoLock ignored = lock.lock()) { closed = terminated; terminated = cause; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java index 107cb15be930..597938b15730 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java @@ -70,6 +70,7 @@ import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.component.DumpableCollection; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Scheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -1748,6 +1749,7 @@ private void complete() */ private class StreamCreator { + private final AutoLock lock = new AutoLock(); private final Queue slots = new ArrayDeque<>(); private Thread flushing; @@ -1825,7 +1827,7 @@ private int reserveSlot(Slot slot, int streamId) { if (streamId <= 0) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { streamId = localStreamIds.getAndAdd(2); slots.offer(slot); @@ -1833,20 +1835,14 @@ private int reserveSlot(Slot slot, int streamId) } else { - synchronized (this) - { - slots.offer(slot); - } + lock.runLocked(() -> slots.offer(slot)); } return streamId; } private void releaseSlotFlushAndFail(Slot slot, Promise promise, Throwable x) { - synchronized (this) - { - slots.remove(slot); - } + lock.runLocked(() -> slots.remove(slot)); flush(); promise.failed(x); } @@ -1870,7 +1866,7 @@ private void flush() while (true) { ControlEntry entry; - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (flushing == null) flushing = thread; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java index e13c7352e49c..ac24709793a1 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java @@ -143,7 +143,7 @@ public void data(DataFrame frame, Callback callback) @Override public void reset(ResetFrame frame, Callback callback) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (isReset()) return; @@ -156,7 +156,7 @@ public void reset(ResetFrame frame, Callback callback) private boolean startWrite(Callback callback) { Throwable failure; - synchronized (this) + try (AutoLock ignored = lock.lock()) { failure = this.failure; if (failure == null && sendCallback == null) @@ -192,27 +192,18 @@ public Object removeAttribute(String key) @Override public boolean isReset() { - synchronized (this) - { - return localReset || remoteReset; - } + return lock.runLocked(() -> localReset || remoteReset); } private boolean isFailed() { - synchronized (this) - { - return failure != null; - } + return lock.runLocked(() -> failure != null); } @Override public boolean isResetOrFailed() { - synchronized (this) - { - return isReset() || isFailed(); - } + return lock.runLocked(() -> isReset() || isFailed()); } @Override @@ -391,7 +382,7 @@ private void onData(DataFrame frame, Callback callback) boolean initial; boolean proceed = false; DataEntry entry = new DataEntry(frame, callback); - try (AutoLock l = lock.lock()) + try (AutoLock ignored = lock.lock()) { dataQueue.offer(entry); initial = dataInitial; @@ -412,7 +403,7 @@ else if (!dataProcess) if (LOG.isDebugEnabled()) LOG.debug("Starting data processing of {} for {}", frame, this); notifyBeforeData(this); - try (AutoLock l = lock.lock()) + try (AutoLock ignored = lock.lock()) { dataProcess = proceed = dataDemand > 0; } @@ -430,7 +421,7 @@ public void demand(long n) throw new IllegalArgumentException("Invalid demand " + n); long demand; boolean proceed = false; - try (AutoLock l = lock.lock()) + try (AutoLock ignored = lock.lock()) { demand = dataDemand = MathUtils.cappedAdd(dataDemand, n); if (!dataProcess) @@ -447,7 +438,7 @@ private void processData() while (true) { DataEntry dataEntry; - try (AutoLock l = lock.lock()) + try (AutoLock ignored = lock.lock()) { if (dataQueue.isEmpty() || dataDemand == 0) { @@ -468,15 +459,12 @@ private void processData() private long demand() { - try (AutoLock l = lock.lock()) - { - return dataDemand; - } + return lock.runLocked(() -> dataDemand); } private void onReset(ResetFrame frame, Callback callback) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { remoteReset = true; failure = new EofException("reset"); @@ -501,10 +489,7 @@ private void onWindowUpdate(WindowUpdateFrame frame, Callback callback) private void onFailure(FailureFrame frame, Callback callback) { - synchronized (this) - { - failure = frame.getFailure(); - } + lock.runLocked(() -> failure = frame.getFailure()); close(); session.removeStream(this); notifyFailure(this, frame, callback); @@ -689,7 +674,7 @@ public void failed(Throwable x) private Callback endWrite() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { Callback callback = sendCallback; sendCallback = null; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2StreamEndPoint.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2StreamEndPoint.java index 5c3e5bbc19ea..e60525ad3e04 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2StreamEndPoint.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2StreamEndPoint.java @@ -35,6 +35,7 @@ import org.eclipse.jetty.io.EofException; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Invocable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +44,7 @@ public abstract class HTTP2StreamEndPoint implements EndPoint { private static final Logger LOG = LoggerFactory.getLogger(HTTP2StreamEndPoint.class); + private final AutoLock lock = new AutoLock(); private final Deque dataQueue = new ArrayDeque<>(); private final AtomicReference writeState = new AtomicReference<>(WriteState.IDLE); private final AtomicReference readCallback = new AtomicReference<>(); @@ -171,11 +173,7 @@ public void close(Throwable cause) @Override public int fill(ByteBuffer sink) throws IOException { - Entry entry; - synchronized (this) - { - entry = dataQueue.poll(); - } + Entry entry = lock.runLocked(dataQueue::poll); if (LOG.isDebugEnabled()) LOG.debug("filled {} on {}", entry, this); @@ -206,10 +204,7 @@ public int fill(ByteBuffer sink) throws IOException if (source.hasRemaining()) { - synchronized (this) - { - dataQueue.offerFirst(entry); - } + lock.runLocked(() -> dataQueue.offerFirst(entry)); } else { @@ -548,19 +543,13 @@ protected void offerFailure(Throwable failure) private void offer(ByteBuffer buffer, Callback callback, Throwable failure) { - synchronized (this) - { - dataQueue.offer(new Entry(buffer, callback, failure)); - } + Entry entry = new Entry(buffer, callback, failure); + lock.runLocked(() -> dataQueue.offer(entry)); } protected void process() { - boolean empty; - synchronized (this) - { - empty = dataQueue.isEmpty(); - } + boolean empty = lock.runLocked(dataQueue::isEmpty); if (!empty) { Callback callback = readCallback.getAndSet(null); diff --git a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java index e2cfc1e86507..24ac5ef4938c 100644 --- a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java +++ b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java @@ -50,6 +50,7 @@ import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -246,6 +247,7 @@ private void notifyContent(HttpExchange exchange, DataFrame frame, Callback call private class ContentNotifier { + private final AutoLock lock = new AutoLock(); private final Queue queue = new ArrayDeque<>(); private final HttpReceiverOverHTTP2 receiver; private DataInfo dataInfo; @@ -269,10 +271,7 @@ private void offer(HttpExchange exchange, DataFrame frame, Callback callback) private void enqueue(DataInfo dataInfo) { - synchronized (this) - { - queue.offer(dataInfo); - } + lock.runLocked(() -> queue.offer(dataInfo)); } private void process(boolean resume) @@ -285,7 +284,7 @@ private void process(boolean resume) return; // Process only if there is demand. - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (!resume && demand() <= 0) { @@ -309,7 +308,7 @@ private void process(boolean resume) } } - synchronized (this) + try (AutoLock ignored = lock.lock()) { dataInfo = queue.poll(); if (LOG.isDebugEnabled()) @@ -347,7 +346,7 @@ private void process(boolean resume) private boolean active(boolean resume) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (active) { @@ -380,7 +379,7 @@ private boolean active(boolean resume) */ private boolean stall() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (resume) { @@ -400,7 +399,7 @@ private boolean stall() private void reset() { dataInfo = null; - synchronized (this) + try (AutoLock ignored = lock.lock()) { queue.clear(); active = false; diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java index efce84ed39e5..7143d43c5214 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java @@ -58,6 +58,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.TypeUtil; +import org.eclipse.jetty.util.thread.AutoLock; public class HTTP2ServerConnection extends HTTP2Connection { @@ -84,7 +85,8 @@ public static boolean isSupportedProtocol(String protocol) return false; } } - + + private final AutoLock lock = new AutoLock(); private final Queue channels = new ArrayDeque<>(); private final List upgradeFrames = new ArrayList<>(); private final AtomicLong totalRequests = new AtomicLong(); @@ -286,27 +288,15 @@ protected ServerHttpChannelOverHTTP2 newServerHttpChannelOverHTTP2(Connector con private void offerHttpChannel(HttpChannelOverHTTP2 channel) { if (isRecycleHttpChannels()) - { - synchronized (this) - { - channels.offer(channel); - } - } + lock.runLocked(() -> channels.offer(channel)); } private HttpChannelOverHTTP2 pollHttpChannel() { if (isRecycleHttpChannels()) - { - synchronized (this) - { - return channels.poll(); - } - } + return lock.runLocked(channels::poll); else - { return null; - } } public boolean upgrade(Request request, HttpFields.Mutable responseFields) diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java index e08993de7467..057bac13eb8f 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java @@ -44,6 +44,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Promise; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -413,6 +414,7 @@ public void abort(Throwable failure) */ private class TransportCallback implements Callback { + private final AutoLock _lock = new AutoLock(); private State _state = State.IDLE; private Callback _callback; private boolean _commit; @@ -420,7 +422,7 @@ private class TransportCallback implements Callback private void reset(Throwable failure) { - assert Thread.holdsLock(this); + assert _lock.isHeldByCurrentThread(); _state = failure != null ? State.FAILED : State.IDLE; _callback = null; _commit = false; @@ -443,7 +445,7 @@ private void abort(Throwable failure) private Throwable sending(Callback callback, boolean commit) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { switch (_state) { @@ -471,7 +473,7 @@ public void succeeded() { Callback callback; boolean commit; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_state != State.SENDING) { @@ -495,7 +497,7 @@ public void failed(Throwable failure) { Callback callback; boolean commit; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_state != State.SENDING) { @@ -517,7 +519,7 @@ public void failed(Throwable failure) private boolean idleTimeout(Throwable failure) { Callback callback = null; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { // Ignore idle timeouts if not writing, // as the application may be suspended. @@ -541,11 +543,7 @@ private boolean idleTimeout(Throwable failure) @Override public InvocationType getInvocationType() { - Callback callback; - synchronized (this) - { - callback = _callback; - } + Callback callback = _lock.runLocked(() -> _callback); return callback != null ? callback.getInvocationType() : Callback.super.getInvocationType(); } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java index bddd34d0bfcd..3975fcccd084 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java @@ -31,7 +31,6 @@ import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.thread.AutoLock; @@ -69,8 +68,7 @@ public class ByteArrayEndPoint extends AbstractEndPoint private static final ByteBuffer EOF = BufferUtil.allocate(0); private final Runnable _runFillable = () -> getFillInterest().fillable(); - private final AutoLock _lock = new AutoLock(); - private final Condition _hasOutput = _lock.newCondition(); + private final AutoLock.WithCondition _lock = new AutoLock.WithCondition(); private final Queue _inQ = new ArrayDeque<>(); private ByteBuffer _out; private boolean _growOutput; @@ -127,9 +125,9 @@ public ByteArrayEndPoint(Scheduler timer, long idleTimeoutMs, ByteBuffer input, public void doShutdownOutput() { super.doShutdownOutput(); - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { - _hasOutput.signalAll(); + lock.signalAll(); } } @@ -137,9 +135,9 @@ public void doShutdownOutput() public void doClose() { super.doClose(); - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { - _hasOutput.signalAll(); + lock.signalAll(); } } @@ -303,11 +301,11 @@ public ByteBuffer waitForOutput(long time, TimeUnit unit) throws InterruptedExce { ByteBuffer b; - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { while (BufferUtil.isEmpty(_out) && !isOutputShutdown()) { - if (!_hasOutput.await(time, unit)) + if (!lock.await(time, unit)) return null; } b = _out; @@ -401,7 +399,7 @@ else if (filled < 0) public boolean flush(ByteBuffer... buffers) throws IOException { boolean flushed = true; - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { if (!isOpen()) throw new IOException("CLOSED"); @@ -438,7 +436,7 @@ public boolean flush(ByteBuffer... buffers) throws IOException if (!idle) { notIdle(); - _hasOutput.signalAll(); + lock.signalAll(); } } return flushed; @@ -447,11 +445,11 @@ public boolean flush(ByteBuffer... buffers) throws IOException @Override public void reset() { - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { _inQ.clear(); - _hasOutput.signalAll(); BufferUtil.clear(_out); + lock.signalAll(); } super.reset(); } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java index 47651f816a03..4f856097ec93 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java @@ -48,6 +48,7 @@ import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.component.DumpableCollection; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.ExecutionStrategy; import org.eclipse.jetty.util.thread.Scheduler; import org.eclipse.jetty.util.thread.strategy.EatWhatYouKill; @@ -79,6 +80,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable } } + private final AutoLock _lock = new AutoLock(); private final AtomicBoolean _started = new AtomicBoolean(false); private boolean _selecting; private final SelectorManager _selectorManager; @@ -252,7 +254,7 @@ private void submit(SelectorUpdate update, boolean lazy) LOG.debug("Queued change lazy={} {} on {}", lazy, update, this); Selector selector = null; - synchronized (ManagedSelector.this) + try (AutoLock ignored = _lock.lock()) { _updates.offer(update); @@ -278,7 +280,7 @@ private void wakeup() LOG.debug("Wakeup {}", this); Selector selector = null; - synchronized (ManagedSelector.this) + try (AutoLock ignored = _lock.lock()) { if (_selecting) { @@ -382,10 +384,7 @@ void destroyEndPoint(EndPoint endPoint, Throwable cause) private int getActionSize() { - synchronized (ManagedSelector.this) - { - return _updates.size(); - } + return _lock.runLocked(() -> _updates.size()); } static int safeReadyOps(SelectionKey selectionKey) @@ -424,7 +423,7 @@ public void dump(Appendable out, String indent) throws IOException { DumpKeys dump = new DumpKeys(); String updatesAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()); - synchronized (ManagedSelector.this) + try (AutoLock ignored = _lock.lock()) { updates = new ArrayList<>(_updates); _updates.addFirst(dump); @@ -514,7 +513,7 @@ public Runnable produce() private void processUpdates() { - synchronized (ManagedSelector.this) + try (AutoLock ignored = _lock.lock()) { Deque updates = _updates; _updates = _updateable; @@ -543,7 +542,7 @@ private void processUpdates() Selector selector; int updates; - synchronized (ManagedSelector.this) + try (AutoLock ignored = _lock.lock()) { updates = _updates.size(); _selecting = updates == 0; @@ -579,7 +578,7 @@ private boolean select() LOG.debug("Selector {} woken up from select, {}/{}/{} selected", selector, selected, selector.selectedKeys().size(), selector.keys().size()); int updates; - synchronized (ManagedSelector.this) + try (AutoLock ignored = _lock.lock()) { // finished selecting _selecting = false; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java index e662c104b588..3d4ce44c6654 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java @@ -29,6 +29,7 @@ import java.nio.channels.SocketChannel; import org.eclipse.jetty.util.BufferUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Invocable; import org.eclipse.jetty.util.thread.Scheduler; import org.slf4j.Logger; @@ -42,6 +43,7 @@ public class SocketChannelEndPoint extends AbstractEndPoint implements ManagedSe { private static final Logger LOG = LoggerFactory.getLogger(SocketChannelEndPoint.class); + private final AutoLock _lock = new AutoLock(); private final SocketChannel _channel; private final ManagedSelector _selector; private SelectionKey _key; @@ -317,7 +319,7 @@ public Runnable onSelected() int readyOps = _key.readyOps(); int oldInterestOps; int newInterestOps; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _updatePending = true; // Remove the readyOps, that here can only be OP_READ or OP_WRITE (or both). @@ -361,7 +363,7 @@ public void updateKey() { int oldInterestOps; int newInterestOps; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _updatePending = false; oldInterestOps = _currentInterestOps; @@ -403,7 +405,7 @@ private void changeInterests(int operation) int oldInterestOps; int newInterestOps; boolean pending; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { pending = _updatePending; oldInterestOps = _desiredInterestOps; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java b/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java index 589c34d7c626..a78b0e863f0a 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/WriterOutputStream.java @@ -33,7 +33,6 @@ public class WriterOutputStream extends OutputStream { protected final Writer _writer; protected final Charset _encoding; - private final byte[] _buf = new byte[1]; public WriterOutputStream(Writer writer, String encoding) { @@ -82,11 +81,9 @@ public void write(byte[] b, int off, int len) } @Override - public synchronized void write(int b) + public void write(int b) throws IOException { - _buf[0] = (byte)b; - write(_buf); + write(new byte[]{(byte)b}); } } - diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java index 25caea62ad83..f771c08f6e86 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java @@ -43,6 +43,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.StringUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Invocable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -104,6 +105,7 @@ private enum FlushState WAIT_FOR_FILL // Waiting for a fill to happen } + private final AutoLock _lock = new AutoLock(); private final List handshakeListeners = new ArrayList<>(); private final ByteBufferPool _bufferPool; private final SSLEngine _sslEngine; @@ -435,7 +437,7 @@ protected void releaseDecryptedInputBuffer() private void releaseEncryptedOutputBuffer() { - if (!Thread.holdsLock(_decryptedEndPoint)) + if (!_lock.isHeldByCurrentThread()) throw new IllegalStateException(); if (_encryptedOutput != null && !_encryptedOutput.hasRemaining()) { @@ -514,7 +516,7 @@ protected void onFillable() { // If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read boolean waitingForFill; - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("onFillable {}", SslConnection.this); @@ -527,10 +529,7 @@ protected void onFillable() if (waitingForFill) { - synchronized (_decryptedEndPoint) - { - waitingForFill = _flushState == FlushState.WAIT_FOR_FILL; - } + waitingForFill = _lock.runLocked(() -> _flushState == FlushState.WAIT_FOR_FILL); if (waitingForFill) fill(BufferUtil.EMPTY_BUFFER); } @@ -545,7 +544,7 @@ protected void onFillableFail(Throwable failure) { // If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read boolean fail = false; - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("onFillableFail {}", SslConnection.this, failure); @@ -594,7 +593,7 @@ public int fill(ByteBuffer buffer) throws IOException { try { - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug(">fill {}", SslConnection.this); @@ -814,7 +813,7 @@ protected void needsFillInterest() boolean fillable; ByteBuffer write = null; boolean interest = false; - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug(">needFillInterest s={}/{} uf={} ei={} di={} {}", @@ -958,7 +957,7 @@ public boolean flush(ByteBuffer... appOuts) throws IOException { try { - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (LOG.isDebugEnabled()) { @@ -1148,7 +1147,7 @@ protected void onIncompleteFlush() { boolean fillInterest = false; ByteBuffer write = null; - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug(">onIncompleteFlush {} {}", SslConnection.this, BufferUtil.toDetailString(_encryptedOutput)); @@ -1242,7 +1241,7 @@ public void doShutdownOutput() { boolean close; boolean flush = false; - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { boolean ishut = endPoint.isInputShutdown(); boolean oshut = endPoint.isOutputShutdown(); @@ -1268,7 +1267,7 @@ public void doShutdownOutput() // If we still can't flush, but we are not closing the endpoint, // let's just flush the encrypted output in the background. ByteBuffer write = null; - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (BufferUtil.hasContent(_encryptedOutput)) { @@ -1280,7 +1279,7 @@ public void doShutdownOutput() { endPoint.write(Callback.from(() -> { - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { _flushState = FlushState.IDLE; releaseEncryptedOutputBuffer(); @@ -1455,7 +1454,7 @@ private boolean isTLS13() private Throwable handleException(Throwable x, String context) { - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (_failure == null) { @@ -1497,7 +1496,7 @@ public void succeeded() { boolean fillable; boolean interested; - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("IncompleteWriteCB succeeded {}", SslConnection.this); @@ -1522,7 +1521,7 @@ else if (fillable) public void failed(final Throwable x) { boolean failFillInterest; - synchronized (_decryptedEndPoint) + try (AutoLock ignored = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("IncompleteWriteCB failed {}", SslConnection.this, x); diff --git a/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java b/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java index 3ad5bdd737ee..1087c4b975e2 100644 --- a/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java +++ b/jetty-io/src/test/java/org/eclipse/jetty/io/SslConnectionTest.java @@ -214,7 +214,7 @@ public void onClose(Throwable cause) } @Override - public synchronized void onFillable() + public void onFillable() { EndPoint endp = getEndPoint(); try diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java index 5d47d117d700..3568b735a7a1 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java @@ -23,6 +23,7 @@ import java.util.List; import org.eclipse.jetty.util.security.Credential; +import org.eclipse.jetty.util.thread.AutoLock; /** * UserInfo @@ -34,10 +35,10 @@ */ public class UserInfo { - - private String _userName; - private Credential _credential; - protected List _roleNames = new ArrayList<>(); + private final AutoLock _lock = new AutoLock(); + protected final List _roleNames = new ArrayList<>(); + private final String _userName; + private final Credential _credential; protected boolean _rolesLoaded = false; /** @@ -80,7 +81,7 @@ public List doFetchRoles() public void fetchRoles() throws Exception { - synchronized (_roleNames) + try (AutoLock ignored = _lock.lock()) { if (!_rolesLoaded) { diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java index 96a9a1f2ba06..6460b9646366 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java @@ -19,7 +19,6 @@ package org.eclipse.jetty.jndi; import java.io.IOException; -import java.util.Collections; import java.util.Hashtable; import java.util.Map; import java.util.WeakHashMap; @@ -32,6 +31,7 @@ import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.util.component.Dumpable; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,12 +41,12 @@ * This is an object factory that produces a jndi naming * context based on a classloader. *

- * It is used for the java:comp context. + * It is used for the {@code java:comp} context. *

- * This object factory is bound at java:comp. When a + * This object factory is bound at {@code java:comp}. When a * lookup arrives for java:comp, this object factory * is invoked and will return a context specific to - * the caller's environment (so producing the java:comp/env + * the caller's environment (so producing the {@code java:comp/env} * specific to a webapp). *

* The context selected is based on classloaders. First @@ -63,19 +63,21 @@ public class ContextFactory implements ObjectFactory /** * Map of classloaders to contexts. */ - private static final Map __contextMap = Collections.synchronizedMap(new WeakHashMap<>()); + private static final Map __contextMap = new WeakHashMap<>(); /** * Threadlocal for injecting a context to use * instead of looking up the map. */ - private static final ThreadLocal __threadContext = new ThreadLocal(); + private static final ThreadLocal __threadContext = new ThreadLocal<>(); /** * Threadlocal for setting a classloader which must be used * when finding the comp context. */ - private static final ThreadLocal __threadClassLoader = new ThreadLocal(); + private static final ThreadLocal __threadClassLoader = new ThreadLocal<>(); + + private static final AutoLock __lock = new AutoLock(); /** * Find or create a context which pertains to a classloader. @@ -90,8 +92,6 @@ public class ContextFactory implements ObjectFactory *

* If there is no current jetty Context, or it has no associated classloader, we * return null. - * - * @see javax.naming.spi.ObjectFactory#getObjectInstance(java.lang.Object, javax.naming.Name, javax.naming.Context, java.util.Hashtable) */ @Override public Object getObjectInstance(Object obj, @@ -101,7 +101,7 @@ public Object getObjectInstance(Object obj, throws Exception { //First, see if we have had a context injected into us to use. - Context ctx = (Context)__threadContext.get(); + Context ctx = __threadContext.get(); if (ctx != null) { if (LOG.isDebugEnabled()) @@ -111,12 +111,12 @@ public Object getObjectInstance(Object obj, //See if there is a classloader to use for finding the comp context //Don't use its parent hierarchy if set. - ClassLoader loader = (ClassLoader)__threadClassLoader.get(); + ClassLoader loader = __threadClassLoader.get(); if (loader != null) { if (LOG.isDebugEnabled()) LOG.debug("Using threadlocal classloader"); - synchronized (__contextMap) + try (AutoLock ignored = __lock.lock()) { ctx = getContextForClassLoader(loader); if (ctx == null) @@ -137,12 +137,12 @@ public Object getObjectInstance(Object obj, { if (LOG.isDebugEnabled()) LOG.debug("Trying thread context classloader"); - synchronized (__contextMap) + try (AutoLock ignored = __lock.lock()) { while (ctx == null && loader != null) { ctx = getContextForClassLoader(loader); - if (ctx == null && loader != null) + if (ctx == null) loader = loader.getParent(); } @@ -161,12 +161,12 @@ public Object getObjectInstance(Object obj, //classloader associated with the current context if (ContextHandler.getCurrentContext() != null) { - if (LOG.isDebugEnabled() && loader != null) + if (LOG.isDebugEnabled()) LOG.debug("Trying classloader of current org.eclipse.jetty.server.handler.ContextHandler"); - synchronized (__contextMap) + try (AutoLock ignored = __lock.lock()) { loader = ContextHandler.getCurrentContext().getContextHandler().getClassLoader(); - ctx = (Context)__contextMap.get(loader); + ctx = __contextMap.get(loader); if (ctx == null && loader != null) { @@ -221,7 +221,7 @@ public Context getContextForClassLoader(ClassLoader loader) if (loader == null) return null; - return (Context)__contextMap.get(loader); + return __lock.runLocked(() -> __contextMap.get(loader)); } /** @@ -233,7 +233,7 @@ public Context getContextForClassLoader(ClassLoader loader) */ public static Context associateContext(final Context ctx) { - Context previous = (Context)__threadContext.get(); + Context previous = __threadContext.get(); __threadContext.set(ctx); return previous; } @@ -245,7 +245,7 @@ public static void disassociateContext(final Context ctx) public static ClassLoader associateClassLoader(final ClassLoader loader) { - ClassLoader prev = (ClassLoader)__threadClassLoader.get(); + ClassLoader prev = __threadClassLoader.get(); __threadClassLoader.set(loader); return prev; } @@ -257,7 +257,7 @@ public static void disassociateClassLoader() public static void dump(Appendable out, String indent) throws IOException { - synchronized (__contextMap) + try (AutoLock ignored = __lock.lock()) { Dumpable.dumpObjects(out, indent, String.format("o.e.j.jndi.ContextFactory@%x", __contextMap.hashCode()), __contextMap); } diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/OSGiClassLoader.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/OSGiClassLoader.java index 256e4e5aa4fc..67d2300ead3f 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/OSGiClassLoader.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/utils/OSGiClassLoader.java @@ -96,37 +96,40 @@ public Class loadClass(String name) throws ClassNotFoundException } @Override - protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - Class c = findLoadedClass(name); - ClassNotFoundException ex = null; - boolean triedParent = false; - - if (c == null) + synchronized (getClassLoadingLock(name)) { - try - { - c = this.findClass(name); - } - catch (ClassNotFoundException e) + Class c = findLoadedClass(name); + ClassNotFoundException ex = null; + boolean triedParent = false; + + if (c == null) { - ex = e; + try + { + c = this.findClass(name); + } + catch (ClassNotFoundException e) + { + ex = e; + } } - } - if (c == null && _parent != null && !triedParent) - c = _parent.loadClass(name); + if (c == null && _parent != null && !triedParent) + c = _parent.loadClass(name); - if (c == null) - throw ex; + if (c == null) + throw ex; - if (resolve) - resolveClass(c); + if (resolve) + resolveClass(c); - if (LOG.isDebugEnabled()) - LOG.debug("loaded " + c + " from " + c.getClassLoader()); + if (LOG.isDebugEnabled()) + LOG.debug("loaded " + c + " from " + c.getClassLoader()); - return c; + return c; + } } @Override diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java index d97750c1f459..9c0aa2ca2d74 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java @@ -46,6 +46,7 @@ import org.eclipse.jetty.util.TypeUtil; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.util.security.Credential; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -282,6 +283,7 @@ private int checkNonce(Digest digest, Request request) private static class Nonce { + private final AutoLock _lock = new AutoLock(); final String _nonce; final long _ts; final BitSet _seen; @@ -295,7 +297,7 @@ public Nonce(String nonce, long ts, int size) public boolean seen(int count) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (count >= _seen.size()) return true; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java index 5aa7e3f1fa9f..f45210e989ab 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java @@ -33,7 +33,6 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; -import java.util.concurrent.locks.Condition; import java.util.stream.Collectors; import org.eclipse.jetty.io.ArrayByteBufferPool; @@ -143,8 +142,7 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co { protected static final Logger LOG = LoggerFactory.getLogger(AbstractConnector.class); - private final AutoLock _lock = new AutoLock(); - private final Condition _setAccepting = _lock.newCondition(); + private final AutoLock.WithCondition _lock = new AutoLock.WithCondition(); private final Map _factories = new LinkedHashMap<>(); // Order is important on server side, so we use a LinkedHashMap private final Server _server; private final Executor _executor; @@ -325,8 +323,10 @@ public boolean isShutdownDone() return false; for (Thread a : _acceptors) + { if (a != null) return false; + } return true; } @@ -446,10 +446,10 @@ public boolean isAccepting() public void setAccepting(boolean accepting) { - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { _accepting = accepting; - _setAccepting.signalAll(); + lock.signalAll(); } } @@ -702,17 +702,17 @@ public void run() if (_acceptorPriorityDelta != 0) thread.setPriority(Math.max(Thread.MIN_PRIORITY, Math.min(Thread.MAX_PRIORITY, priority + _acceptorPriorityDelta))); - _acceptors[_id] = thread; + _lock.runLocked(() -> _acceptors[_id] = thread); try { while (isRunning() && !_shutdown.isShutdown()) { - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { if (!_accepting && isRunning()) { - _setAccepting.await(); + lock.await(); continue; } } @@ -738,10 +738,8 @@ public void run() if (_acceptorPriorityDelta != 0) thread.setPriority(priority); - synchronized (AbstractConnector.this) - { - _acceptors[_id] = null; - } + _lock.runLocked(() -> _acceptors[_id] = null); + Shutdown shutdown = _shutdown; if (shutdown != null) shutdown.check(); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AcceptRateLimit.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AcceptRateLimit.java index 28d9ca77db4b..c8e69d34db04 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AcceptRateLimit.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AcceptRateLimit.java @@ -31,6 +31,7 @@ import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.component.Container; import org.eclipse.jetty.util.statistic.RateStatistic; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Scheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -64,6 +65,7 @@ public class AcceptRateLimit extends AbstractLifeCycle implements SelectorManage { private static final Logger LOG = LoggerFactory.getLogger(AcceptRateLimit.class); + private final AutoLock _lock = new AutoLock(); private final Server _server; private final List _connectors = new ArrayList<>(); private final Rate _rate; @@ -123,7 +125,7 @@ public long getMaxRate() @ManagedOperation(value = "Resets the accept rate", impact = "ACTION") public void reset() { - synchronized (_rate) + try (AutoLock ignored = _lock.lock()) { _rate.reset(); if (_limiting) @@ -142,7 +144,7 @@ protected void age(long period, TimeUnit units) @Override protected void doStart() throws Exception { - synchronized (_rate) + try (AutoLock ignored = _lock.lock()) { if (_server != null) { @@ -156,7 +158,7 @@ protected void doStart() throws Exception } if (LOG.isDebugEnabled()) - LOG.debug("AcceptLimit accept<{} rate<{} in {} for {}", _acceptRateLimit, _rate, _connectors); + LOG.debug("AcceptLimit accept<{} rate<{} in {}", _acceptRateLimit, _rate, _connectors); for (AbstractConnector c : _connectors) { @@ -168,7 +170,7 @@ protected void doStart() throws Exception @Override protected void doStop() throws Exception { - synchronized (_rate) + try (AutoLock ignored = _lock.lock()) { if (_task != null) _task.cancel(); @@ -203,19 +205,16 @@ protected void unlimit() @Override public void onAccepting(SelectableChannel channel) { - synchronized (_rate) + try (AutoLock ignored = _lock.lock()) { int rate = _rate.record(); if (LOG.isDebugEnabled()) - { LOG.debug("onAccepting rate {}/{} for {} {}", rate, _acceptRateLimit, _rate, channel); - } if (rate > _acceptRateLimit) { if (!_limiting) { _limiting = true; - LOG.warn("AcceptLimit rate exceeded {}>{} on {}", rate, _acceptRateLimit, _connectors); limit(); } @@ -238,7 +237,7 @@ private void schedule() @Override public void run() { - synchronized (_rate) + try (AutoLock ignored = _lock.lock()) { _task = null; if (!isRunning()) @@ -258,7 +257,7 @@ public void run() } } - private final class Rate extends RateStatistic + private static final class Rate extends RateStatistic { private Rate(long period, TimeUnit units) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncRequestLogWriter.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncRequestLogWriter.java index f1a9ba6cb880..a6f786407351 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncRequestLogWriter.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncRequestLogWriter.java @@ -92,7 +92,7 @@ public void run() } @Override - protected synchronized void doStart() throws Exception + protected void doStart() throws Exception { super.doStart(); _thread = new AsyncRequestLogWriter.WriterThread(); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java index 054923a2862e..1136330806be 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java @@ -33,6 +33,7 @@ import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.component.Container; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,9 +63,10 @@ public class ConnectionLimit extends AbstractLifeCycle implements Listener, Sele { private static final Logger LOG = LoggerFactory.getLogger(ConnectionLimit.class); - private final Server _server; + private final AutoLock _lock = new AutoLock(); private final List _connectors = new ArrayList<>(); private final Set _accepting = new HashSet<>(); + private final Server _server; private int _connections; private int _maxConnections; private long _idleTimeout; @@ -108,33 +110,24 @@ public void setIdleTimeout(long idleTimeout) @ManagedAttribute("The maximum number of connections allowed") public int getMaxConnections() { - synchronized (this) - { - return _maxConnections; - } + return _lock.runLocked(() -> _maxConnections); } public void setMaxConnections(int max) { - synchronized (this) - { - _maxConnections = max; - } + _lock.runLocked(() -> _maxConnections = max); } @ManagedAttribute("The current number of connections ") public int getConnections() { - synchronized (this) - { - return _connections; - } + return _lock.runLocked(() -> _connections); } @Override protected void doStart() throws Exception { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_server != null) { @@ -160,7 +153,7 @@ protected void doStart() throws Exception @Override protected void doStop() throws Exception { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { for (AbstractConnector c : _connectors) { @@ -229,7 +222,7 @@ protected void unlimit() @Override public void onAccepting(SelectableChannel channel) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _accepting.add(channel); if (LOG.isDebugEnabled()) @@ -241,7 +234,7 @@ public void onAccepting(SelectableChannel channel) @Override public void onAcceptFailed(SelectableChannel channel, Throwable cause) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _accepting.remove(channel); if (LOG.isDebugEnabled()) @@ -258,7 +251,7 @@ public void onAccepted(SelectableChannel channel) @Override public void onOpened(Connection connection) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _accepting.remove(connection.getEndPoint().getTransport()); _connections++; @@ -271,7 +264,7 @@ public void onOpened(Connection connection) @Override public void onClosed(Connection connection) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _connections--; if (LOG.isDebugEnabled()) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java b/jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java index e67ad99993d2..3126306e8639 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java @@ -408,7 +408,7 @@ public String getFormatString() * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() */ @Override - protected synchronized void doStart() throws Exception + protected void doStart() throws Exception { if (_ignorePaths != null && _ignorePaths.length > 0) { diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java index 52bf1ab29040..7fd6830b42fd 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import javax.servlet.AsyncListener; import javax.servlet.ServletContext; import javax.servlet.ServletResponse; @@ -32,6 +33,7 @@ import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandler.Context; import org.eclipse.jetty.server.handler.ErrorHandler; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Scheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -144,6 +146,7 @@ public enum Action WAIT, // Wait for further events } + private final AutoLock _lock = new AutoLock(); private final HttpChannel _channel; private List _asyncListeners; private State _state = State.IDLE; @@ -161,17 +164,24 @@ protected HttpChannelState(HttpChannel channel) _channel = channel; } + AutoLock lock() + { + return _lock.lock(); + } + + R runLocked(Supplier code) + { + return _lock.runLocked(code); + } + public State getState() { - synchronized (this) - { - return _state; - } + return runLocked(() -> _state); } public void addListener(AsyncListener listener) { - synchronized (this) + try (AutoLock ignored = lock()) { if (_asyncListeners == null) _asyncListeners = new ArrayList<>(); @@ -181,7 +191,7 @@ public void addListener(AsyncListener listener) public boolean hasListener(AsyncListener listener) { - synchronized (this) + try (AutoLock ignored = lock()) { if (_asyncListeners == null) return false; @@ -200,43 +210,28 @@ public boolean hasListener(AsyncListener listener) public boolean isSendError() { - synchronized (this) - { - return _sendError; - } + return runLocked(() -> _sendError); } public void setTimeout(long ms) { - synchronized (this) - { - _timeoutMs = ms; - } + runLocked(() -> _timeoutMs = ms); } public long getTimeout() { - synchronized (this) - { - return _timeoutMs; - } + return runLocked(() -> _timeoutMs); } public AsyncContextEvent getAsyncContextEvent() { - synchronized (this) - { - return _event; - } + return runLocked(() -> _event); } @Override public String toString() { - synchronized (this) - { - return toStringLocked(); - } + return runLocked(this::toStringLocked); } private String toStringLocked() @@ -262,15 +257,12 @@ private String getStatusStringLocked() public String getStatusString() { - synchronized (this) - { - return getStatusStringLocked(); - } + return runLocked(this::getStatusStringLocked); } public boolean commitResponse() { - synchronized (this) + try (AutoLock ignored = lock()) { switch (_outputState) { @@ -286,7 +278,7 @@ public boolean commitResponse() public boolean partialResponse() { - synchronized (this) + try (AutoLock ignored = lock()) { switch (_outputState) { @@ -302,7 +294,7 @@ public boolean partialResponse() public boolean completeResponse() { - synchronized (this) + try (AutoLock ignored = lock()) { switch (_outputState) { @@ -319,7 +311,7 @@ public boolean completeResponse() public boolean isResponseCommitted() { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { switch (_outputState) { @@ -333,15 +325,12 @@ public boolean isResponseCommitted() public boolean isResponseCompleted() { - synchronized (this) - { - return _outputState == OutputState.COMPLETED; - } + return runLocked(() -> _outputState == OutputState.COMPLETED); } public boolean abortResponse() { - synchronized (this) + try (AutoLock ignored = lock()) { switch (_outputState) { @@ -365,7 +354,7 @@ public boolean abortResponse() */ public Action handling() { - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("handling {}", toStringLocked()); @@ -407,7 +396,7 @@ public Action handling() */ protected Action unhandle() { - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("unhandle {}", toStringLocked()); @@ -526,7 +515,7 @@ public void startAsync(AsyncContextEvent event) { final List lastAsyncListeners; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("startAsync {}", toStringLocked()); @@ -575,7 +564,7 @@ public void dispatch(ServletContext context, String path) { boolean dispatch = false; AsyncContextEvent event; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("dispatch {} -> {}", toStringLocked(), path); @@ -611,7 +600,7 @@ public void dispatch(ServletContext context, String path) protected void timeout() { boolean dispatch = false; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("Timeout {}", toStringLocked()); @@ -639,7 +628,7 @@ protected void onTimeout() { final List listeners; AsyncContextEvent event; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onTimeout {}", toStringLocked()); @@ -687,7 +676,7 @@ public void complete() { boolean handle = false; AsyncContextEvent event; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("complete {}", toStringLocked()); @@ -725,7 +714,7 @@ public void asyncError(Throwable failure) // actually handled by #thrownException AsyncContextEvent event = null; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("asyncError " + toStringLocked(), failure); @@ -756,7 +745,7 @@ protected void onError(Throwable th) { final AsyncContextEvent asyncEvent; final List asyncListeners; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("thrownException " + getStatusStringLocked(), th); @@ -820,7 +809,7 @@ protected void onError(Throwable th) }); // check the actions of the listeners - synchronized (this) + try (AutoLock ignored = lock()) { if (_requestState == RequestState.ASYNC && !_sendError) { @@ -892,7 +881,7 @@ public void sendError(int code, String message) if (message == null) message = HttpStatus.getMessage(code); - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("sendError {}", toStringLocked()); @@ -933,7 +922,7 @@ public void sendError(int code, String message) protected void completing() { - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("completing {}", toStringLocked()); @@ -954,7 +943,7 @@ protected void completed(Throwable failure) final AsyncContextEvent event; boolean handle = false; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("completed {}", toStringLocked()); @@ -1008,7 +997,7 @@ protected void completed(Throwable failure) } event.completed(); - synchronized (this) + try (AutoLock ignored = lock()) { _requestState = RequestState.COMPLETED; if (_state == State.WAITING) @@ -1026,7 +1015,7 @@ protected void completed(Throwable failure) protected void recycle() { cancelTimeout(); - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("recycle {}", toStringLocked()); @@ -1055,7 +1044,7 @@ protected void recycle() public void upgrade() { cancelTimeout(); - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("upgrade {}", toStringLocked()); @@ -1085,11 +1074,7 @@ protected void scheduleDispatch() protected void cancelTimeout() { - final AsyncContextEvent event; - synchronized (this) - { - event = _event; - } + AsyncContextEvent event = runLocked(() -> _event); cancelTimeout(event); } @@ -1101,48 +1086,33 @@ protected void cancelTimeout(AsyncContextEvent event) public boolean isIdle() { - synchronized (this) - { - return _state == State.IDLE; - } + return runLocked(() -> _state == State.IDLE); } public boolean isExpired() { - synchronized (this) - { - // TODO review - return _requestState == RequestState.EXPIRE || _requestState == RequestState.EXPIRING; - } + // TODO review + return runLocked(() -> _requestState == RequestState.EXPIRE || _requestState == RequestState.EXPIRING); } public boolean isInitial() { - synchronized (this) - { - return _initial; - } + return runLocked(() -> _initial); } public boolean isSuspended() { - synchronized (this) - { - return _state == State.WAITING || _state == State.HANDLING && _requestState == RequestState.ASYNC; - } + return runLocked(() -> _state == State.WAITING || _state == State.HANDLING && _requestState == RequestState.ASYNC); } boolean isCompleted() { - synchronized (this) - { - return _requestState == RequestState.COMPLETED; - } + return runLocked(() -> _requestState == RequestState.COMPLETED); } public boolean isAsyncStarted() { - synchronized (this) + try (AutoLock ignored = lock()) { if (_state == State.HANDLING) return _requestState != RequestState.BLOCKING; @@ -1152,10 +1122,7 @@ public boolean isAsyncStarted() public boolean isAsync() { - synchronized (this) - { - return !_initial || _requestState != RequestState.BLOCKING; - } + return runLocked(() -> !_initial || _requestState != RequestState.BLOCKING); } public Request getBaseRequest() @@ -1170,12 +1137,7 @@ public HttpChannel getHttpChannel() public ContextHandler getContextHandler() { - final AsyncContextEvent event; - synchronized (this) - { - event = _event; - } - return getContextHandler(event); + return getContextHandler(getAsyncContextEvent()); } ContextHandler getContextHandler(AsyncContextEvent event) @@ -1191,12 +1153,7 @@ ContextHandler getContextHandler(AsyncContextEvent event) public ServletResponse getServletResponse() { - final AsyncContextEvent event; - synchronized (this) - { - event = _event; - } - return getServletResponse(event); + return getServletResponse(getAsyncContextEvent()); } public ServletResponse getServletResponse(AsyncContextEvent event) @@ -1240,7 +1197,7 @@ public void setAttribute(String name, Object attribute) public void onReadUnready() { boolean interested = false; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onReadUnready {}", toStringLocked()); @@ -1286,7 +1243,7 @@ public void onReadUnready() public boolean onContentAdded() { boolean woken = false; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onContentAdded {}", toStringLocked()); @@ -1329,7 +1286,7 @@ public boolean onContentAdded() public boolean onReadReady() { boolean woken = false; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onReadReady {}", toStringLocked()); @@ -1362,7 +1319,7 @@ public boolean onReadReady() public boolean onReadPossible() { boolean woken = false; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onReadPossible {}", toStringLocked()); @@ -1394,7 +1351,7 @@ public boolean onReadPossible() public boolean onReadEof() { boolean woken = false; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onEof {}", toStringLocked()); @@ -1414,7 +1371,7 @@ public boolean onWritePossible() { boolean wake = false; - synchronized (this) + try (AutoLock ignored = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onWritePossible {}", toStringLocked()); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpInput.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpInput.java index ed4f6bd240ba..34d7e6302995 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpInput.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpInput.java @@ -36,6 +36,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.component.Destroyable; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -125,6 +126,7 @@ public void destroy() static final Content EOF_CONTENT = new EofContent("EOF"); static final Content EARLY_EOF_CONTENT = new EofContent("EARLY_EOF"); + private final AutoLock.WithCondition _lock = new AutoLock.WithCondition(); private final byte[] _oneByteBuffer = new byte[1]; private Content _content; private Content _intercepted; @@ -151,7 +153,7 @@ protected HttpChannelState getHttpChannelState() public void recycle() { - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { if (_content != null) _content.failed(null); @@ -212,7 +214,7 @@ public int available() { int available = 0; boolean woken = false; - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { if (_content == null) _content = _inputQ.poll(); @@ -260,7 +262,7 @@ public int read(byte[] b, int off, int len) throws IOException { boolean wake = false; int l; - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { // Calculate minimum request rate for DOS protection long minRequestDataRate = _channelState.getHttpChannel().getHttpConfiguration().getMinRequestDataRate(); @@ -333,7 +335,7 @@ protected void produceContent() throws IOException */ public void asyncReadProduce() throws IOException { - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { produceContent(); } @@ -539,9 +541,9 @@ protected void blockForContent() throws IOException if (LOG.isDebugEnabled()) LOG.debug("{} blocking for content timeout={}", this, timeout); if (timeout > 0) - _inputQ.wait(timeout); + _lock.await(timeout, TimeUnit.MILLISECONDS); else - _inputQ.wait(); + _lock.await(); loop = true; } @@ -560,7 +562,7 @@ protected void blockForContent() throws IOException */ public boolean addContent(Content content) { - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { _waitingForContent = false; if (_firstByteTimeStamp == -1) @@ -594,26 +596,20 @@ public boolean addContent(Content content) public boolean hasContent() { - synchronized (_inputQ) - { - return _content != null || _inputQ.size() > 0; - } + return _lock.runLocked(() -> _content != null || _inputQ.size() > 0); } public void unblock() { - synchronized (_inputQ) + try (AutoLock.WithCondition lock = _lock.lock()) { - _inputQ.notify(); + lock.signal(); } } public long getContentConsumed() { - synchronized (_inputQ) - { - return _contentConsumed; - } + return _lock.runLocked(() -> _contentConsumed); } /** @@ -640,7 +636,7 @@ public boolean eof() public boolean consumeAll() { - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { try { @@ -669,27 +665,18 @@ public boolean consumeAll() public boolean isError() { - synchronized (_inputQ) - { - return _state instanceof ErrorState; - } + return _lock.runLocked(() -> _state instanceof ErrorState); } public boolean isAsync() { - synchronized (_inputQ) - { - return _state == ASYNC; - } + return _lock.runLocked(() -> _state == ASYNC); } @Override public boolean isFinished() { - synchronized (_inputQ) - { - return _state instanceof EOFState; - } + return _lock.runLocked(() -> _state instanceof EOFState); } @Override @@ -697,7 +684,7 @@ public boolean isReady() { try { - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { if (_listener == null) return true; @@ -725,7 +712,7 @@ public void setReadListener(ReadListener readListener) boolean woken = false; try { - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { if (_listener != null) throw new IllegalStateException("ReadListener already set"); @@ -773,7 +760,7 @@ else if (_state == EOF) public boolean onIdleTimeout(Throwable x) { - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { boolean neverDispatched = getHttpChannelState().isIdle(); if ((_waitingForContent || neverDispatched) && !isError()) @@ -788,7 +775,7 @@ public boolean onIdleTimeout(Throwable x) public boolean failed(Throwable x) { - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { // Errors may be reported multiple times, for example // a local idle timeout and a remote I/O failure. @@ -818,7 +805,7 @@ private boolean wakeup() { if (_listener != null) return _channelState.onContentAdded(); - _inputQ.notify(); + _lock.signal(); return false; } @@ -833,7 +820,7 @@ public void run() Throwable error; boolean aeof = false; - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { listener = _listener; @@ -922,7 +909,7 @@ public String toString() long consumed; int q; Content content; - synchronized (_inputQ) + try (AutoLock ignored = _lock.lock()) { state = _state; consumed = _contentConsumed; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpOutput.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpOutput.java index 3101ed88bbee..70c3c5f5a73f 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpOutput.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpOutput.java @@ -44,6 +44,7 @@ import org.eclipse.jetty.util.IteratingCallback; import org.eclipse.jetty.util.SharedBlockingCallback; import org.eclipse.jetty.util.SharedBlockingCallback.Blocker; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -238,10 +239,7 @@ public long getWritten() public void reopen() { - synchronized (_channelState) - { - _softClose = false; - } + _channelState.runLocked(() -> _softClose = false); } protected Blocker acquireWriteBlockingCallback() throws IOException @@ -278,7 +276,7 @@ private void onWriteComplete(boolean last, Throwable failure) boolean wake = false; Callback closedCallback = null; ByteBuffer closeContent = null; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { if (LOG.isDebugEnabled()) state = stateString(); @@ -381,10 +379,7 @@ private int maximizeAggregateSpace() public void softClose() { - synchronized (_channelState) - { - _softClose = true; - } + _channelState.runLocked(() -> _softClose = true); } public void complete(Callback callback) @@ -397,7 +392,7 @@ public void complete(Callback callback) boolean succeeded = false; Throwable error = null; ByteBuffer content = null; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { switch (_state) { @@ -473,7 +468,7 @@ public void complete(Callback callback) */ public void completed(Throwable failure) { - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { _state = State.CLOSED; releaseBuffer(failure); @@ -485,7 +480,7 @@ public void close() throws IOException { ByteBuffer content = null; Blocker blocker = null; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { if (_onError != null) { @@ -602,10 +597,7 @@ public void close() throws IOException public ByteBuffer getBuffer() { - synchronized (_channelState) - { - return acquireBuffer(); - } + return _channelState.runLocked(this::acquireBuffer); } private ByteBuffer acquireBuffer() @@ -630,15 +622,12 @@ private void releaseBuffer(Throwable failure) public boolean isClosed() { - synchronized (_channelState) - { - return _softClose || (_state != State.OPEN); - } + return _channelState.runLocked(() -> _softClose || (_state != State.OPEN)); } public boolean isAsync() { - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { switch (_apiState) { @@ -657,7 +646,7 @@ public boolean isAsync() public void flush() throws IOException { ByteBuffer content = null; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { switch (_state) { @@ -740,7 +729,7 @@ public void write(byte[] b, int off, int len) throws IOException // Async or Blocking ? boolean async; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { checkWritable(); long written = _written + len; @@ -871,7 +860,7 @@ public void write(ByteBuffer buffer) throws IOException // Async or Blocking ? boolean async; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { checkWritable(); long written = _written + len; @@ -946,7 +935,7 @@ public void write(int b) throws IOException // Async or Blocking ? boolean async = false; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { checkWritable(); long written = _written + 1; @@ -1209,7 +1198,7 @@ public void sendContent(ReadableByteChannel in, Callback callback) private boolean prepareSendContent(int len, Callback callback) { - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { if (BufferUtil.hasContent(_aggregate)) { @@ -1347,7 +1336,7 @@ public void onFlushed(long bytes) throws IOException public void recycle() { - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { _state = State.OPEN; _apiState = ApiState.BLOCKING; @@ -1370,7 +1359,7 @@ public void recycle() public void resetBuffer() { - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { _interceptor.resetBuffer(); if (BufferUtil.hasContent(_aggregate)) @@ -1385,7 +1374,7 @@ public void setWriteListener(WriteListener writeListener) if (!_channel.getState().isAsync()) throw new IllegalStateException("!ASYNC: " + stateString()); boolean wake; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { if (_apiState != ApiState.BLOCKING) throw new IllegalStateException("!OPEN" + stateString()); @@ -1400,7 +1389,7 @@ public void setWriteListener(WriteListener writeListener) @Override public boolean isReady() { - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { switch (_apiState) { @@ -1431,7 +1420,7 @@ public void run() { Throwable error = null; - synchronized (_channelState) + try (AutoLock ignored = _channelState.lock()) { if (_onError != null) { @@ -1482,10 +1471,7 @@ private String stateString() @Override public String toString() { - synchronized (_channelState) - { - return String.format("%s@%x{%s}", this.getClass().getSimpleName(), hashCode(), stateString()); - } + return _channelState.runLocked(() -> String.format("%s@%x{%s}", this.getClass().getSimpleName(), hashCode(), stateString())); } private abstract class ChannelWriteCB extends IteratingCallback diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java b/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java index 12b9555fbadc..91101c544f66 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java @@ -45,6 +45,7 @@ import org.eclipse.jetty.util.MultiMap; import org.eclipse.jetty.util.QuotedStringTokenizer; import org.eclipse.jetty.util.StringUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -90,6 +91,8 @@ private enum State } private static final Logger LOG = LoggerFactory.getLogger(MultiPartFormInputStream.class); + + private final AutoLock _lock = new AutoLock(); private final MultiMap _parts = new MultiMap<>(); private final InputStream _in; private final MultipartConfigElement _config; @@ -100,7 +103,7 @@ private enum State private volatile boolean _deleteOnExit; private volatile boolean _writeFilesWithFilenames; private volatile int _bufferSize = 16 * 1024; - private State state = State.UNPARSED; + private State _state = State.UNPARSED; public class MultiPart implements Part { @@ -375,7 +378,7 @@ public MultiPartFormInputStream(InputStream in, String contentType, MultipartCon if (((ServletInputStream)in).isFinished()) { _in = null; - state = State.PARSED; + _state = State.PARSED; return; } } @@ -407,24 +410,24 @@ public boolean isEmpty() */ public void deleteParts() { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { - switch (state) + switch (_state) { case DELETED: case DELETING: return; case PARSING: - state = State.DELETING; + _state = State.DELETING; return; case UNPARSED: - state = State.DELETED; + _state = State.DELETED; return; case PARSED: - state = State.DELETED; + _state = State.DELETED; break; } } @@ -510,19 +513,19 @@ protected void throwIfError() throws IOException */ protected void parse() { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { - switch (state) + switch (_state) { case UNPARSED: - state = State.PARSING; + _state = State.PARSING; break; case PARSED: return; default: - _err = new IOException(state.name()); + _err = new IOException(_state.name()); return; } } @@ -563,11 +566,11 @@ else if ("".equals(_config.getLocation())) while (true) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { - if (state != State.PARSING) + if (_state != State.PARSING) { - _err = new IOException(state.name()); + _err = new IOException(_state.name()); return; } } @@ -629,21 +632,21 @@ else if (len == -1) finally { boolean cleanup = false; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { - switch (state) + switch (_state) { case PARSING: - state = State.PARSED; + _state = State.PARSED; break; case DELETING: - state = State.DELETED; + _state = State.DELETED; cleanup = true; break; default: - _err = new IllegalStateException(state.name()); + _err = new IllegalStateException(_state.name()); } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/RequestLogWriter.java b/jetty-server/src/main/java/org/eclipse/jetty/server/RequestLogWriter.java index b9c3b9e666d0..2773ffdbe674 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/RequestLogWriter.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/RequestLogWriter.java @@ -28,6 +28,7 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.AbstractLifeCycle; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +40,7 @@ public class RequestLogWriter extends AbstractLifeCycle implements RequestLog.Wr { private static final Logger LOG = LoggerFactory.getLogger(RequestLogWriter.class); + private final AutoLock _lock = new AutoLock(); private String _filename; private boolean _append; private int _retainDays; @@ -175,7 +177,7 @@ public String getFilenameDateFormat() @Override public void write(String requestEntry) throws IOException { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_writer == null) return; @@ -186,21 +188,21 @@ public void write(String requestEntry) throws IOException } @Override - protected synchronized void doStart() throws Exception + protected void doStart() throws Exception { - if (_filename != null) - { - _fileOut = new RolloverFileOutputStream(_filename, _append, _retainDays, TimeZone.getTimeZone(getTimeZone()), _filenameDateFormat, null); - _closeOut = true; - LOG.info("Opened " + getDatedFilename()); - } - else - _fileOut = System.err; - - _out = _fileOut; - - synchronized (this) + try (AutoLock ignored = _lock.lock()) { + if (_filename != null) + { + _fileOut = new RolloverFileOutputStream(_filename, _append, _retainDays, TimeZone.getTimeZone(getTimeZone()), _filenameDateFormat, null); + _closeOut = true; + LOG.info("Opened " + getDatedFilename()); + } + else + { + _fileOut = System.err; + } + _out = _fileOut; _writer = new OutputStreamWriter(_out); } super.doStart(); @@ -220,9 +222,9 @@ public String getTimeZone() @Override protected void doStop() throws Exception { - synchronized (this) + super.doStop(); + try (AutoLock ignored = _lock.lock()) { - super.doStop(); try { if (_writer != null) @@ -233,6 +235,7 @@ protected void doStop() throws Exception LOG.trace("IGNORED", e); } if (_out != null && _closeOut) + { try { _out.close(); @@ -241,6 +244,7 @@ protected void doStop() throws Exception { LOG.trace("IGNORED", e); } + } _out = null; _fileOut = null; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceService.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceService.java index f5b9addebcce..3be87aa28cbb 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceService.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceService.java @@ -377,22 +377,19 @@ protected void sendWelcome(HttpContent content, String pathInContext, boolean en if (!endsWithSlash) { StringBuffer buf = request.getRequestURL(); - synchronized (buf) + int param = buf.lastIndexOf(";"); + if (param < 0) + buf.append('/'); + else + buf.insert(param, '/'); + String q = request.getQueryString(); + if (q != null && q.length() != 0) { - int param = buf.lastIndexOf(";"); - if (param < 0) - buf.append('/'); - else - buf.insert(param, '/'); - String q = request.getQueryString(); - if (q != null && q.length() != 0) - { - buf.append('?'); - buf.append(q); - } - response.setContentLength(0); - response.sendRedirect(response.encodeRedirectURL(buf.toString())); + buf.append('?'); + buf.append(q); } + response.setContentLength(0); + response.sendRedirect(response.encodeRedirectURL(buf.toString())); return; } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ShutdownMonitor.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ShutdownMonitor.java index 42477dcf50f9..8d32b47ee700 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ShutdownMonitor.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ShutdownMonitor.java @@ -37,6 +37,7 @@ import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.component.Destroyable; import org.eclipse.jetty.util.component.LifeCycle; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.ShutdownThread; /** @@ -85,6 +86,7 @@ public static boolean isRegistered(LifeCycle lifeCycle) return getInstance().containsLifeCycle(lifeCycle); } + private final AutoLock.WithCondition _lock = new AutoLock.WithCondition(); private final Set _lifeCycles = new LinkedHashSet<>(); private boolean debug; private final String host; @@ -96,8 +98,9 @@ public static boolean isRegistered(LifeCycle lifeCycle) /** * Creates a ShutdownMonitor using configuration from the System properties. *

- * STOP.PORT = the port to listen on (empty, null, or values less than 0 disable the stop ability)
- * STOP.KEY = the magic key/passphrase to allow the stop
+ * {@code STOP.PORT} = the port to listen on (empty, null, or values less than 0 disable the stop ability) + *
+ * {@code STOP.KEY} = the magic key/passphrase to allow the stop
*

* Note: server socket will only listen on localhost, and a successful stop will issue a System.exit() call. */ @@ -112,26 +115,17 @@ private ShutdownMonitor() private void addLifeCycles(LifeCycle... lifeCycles) { - synchronized (this) - { - _lifeCycles.addAll(Arrays.asList(lifeCycles)); - } + _lock.runLocked(() -> _lifeCycles.addAll(Arrays.asList(lifeCycles))); } private void removeLifeCycle(LifeCycle lifeCycle) { - synchronized (this) - { - _lifeCycles.remove(lifeCycle); - } + _lock.runLocked(() -> _lifeCycles.remove(lifeCycle)); } private boolean containsLifeCycle(LifeCycle lifeCycle) { - synchronized (this) - { - return _lifeCycles.contains(lifeCycle); - } + return _lock.runLocked(() -> _lifeCycles.contains(lifeCycle)); } private void debug(String format, Object... args) @@ -148,26 +142,17 @@ private void debug(Throwable t) public String getKey() { - synchronized (this) - { - return key; - } + return _lock.runLocked(() -> key); } public int getPort() { - synchronized (this) - { - return port; - } + return _lock.runLocked(() -> port); } public boolean isExitVm() { - synchronized (this) - { - return exitVm; - } + return _lock.runLocked(() -> exitVm); } public void setDebug(boolean flag) @@ -180,7 +165,7 @@ public void setDebug(boolean flag) */ public void setExitVm(boolean exitVm) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (alive) throw new IllegalStateException("ShutdownMonitor already started"); @@ -190,7 +175,7 @@ public void setExitVm(boolean exitVm) public void setKey(String key) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (alive) throw new IllegalStateException("ShutdownMonitor already started"); @@ -200,7 +185,7 @@ public void setKey(String key) public void setPort(int port) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (alive) throw new IllegalStateException("ShutdownMonitor already started"); @@ -210,7 +195,7 @@ public void setPort(int port) protected void start() throws Exception { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (alive) { @@ -231,31 +216,28 @@ protected void start() throws Exception private void stop() { - synchronized (this) + try (AutoLock.WithCondition lock = _lock.lock()) { alive = false; - notifyAll(); + lock.signalAll(); } } // For test purposes only. void await() throws InterruptedException { - synchronized (this) + try (AutoLock.WithCondition lock = _lock.lock()) { while (alive) { - wait(); + lock.await(); } } } protected boolean isAlive() { - synchronized (this) - { - return alive; - } + return _lock.runLocked(() -> alive); } private ServerSocket listen() @@ -429,12 +411,7 @@ private void informClient(OutputStream out, String message) throws IOException private void stopLifeCycles(Predicate predicate, boolean destroy) { - List lifeCycles = new ArrayList<>(); - synchronized (this) - { - lifeCycles.addAll(_lifeCycles); - } - + List lifeCycles = _lock.runLocked(() -> new ArrayList<>(_lifeCycles)); for (LifeCycle l : lifeCycles) { try diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/Slf4jRequestLogWriter.java b/jetty-server/src/main/java/org/eclipse/jetty/server/Slf4jRequestLogWriter.java index e5faf948df7c..3dad95333a06 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/Slf4jRequestLogWriter.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/Slf4jRequestLogWriter.java @@ -63,7 +63,7 @@ public void write(String requestEntry) throws IOException } @Override - protected synchronized void doStart() throws Exception + protected void doStart() throws Exception { logger = LoggerFactory.getLogger(loggerName); super.doStart(); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java index edf9a20139a8..941bcacbee08 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java @@ -86,6 +86,7 @@ import org.eclipse.jetty.util.component.DumpableCollection; import org.eclipse.jetty.util.component.Graceful; import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -128,19 +129,12 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu }; public static final int DEFAULT_LISTENER_TYPE_INDEX = 1; - public static final int EXTENDED_LISTENER_TYPE_INDEX = 0; - private static final String UNIMPLEMENTED_USE_SERVLET_CONTEXT_HANDLER = "Unimplemented {} - use org.eclipse.jetty.servlet.ServletContextHandler"; - private static final Logger LOG = LoggerFactory.getLogger(ContextHandler.class); - private static final ThreadLocal __context = new ThreadLocal<>(); - private static String __serverInfo = "jetty/" + Server.getVersion(); - public static final String MANAGED_ATTRIBUTES = "org.eclipse.jetty.server.context.ManagedAttributes"; - public static final String MAX_FORM_KEYS_KEY = "org.eclipse.jetty.server.Request.maxFormKeys"; public static final String MAX_FORM_CONTENT_SIZE_KEY = "org.eclipse.jetty.server.Request.maxFormContentSize"; public static final int DEFAULT_MAX_FORM_KEYS = 1000; @@ -182,7 +176,8 @@ public enum ContextStatus INITIALIZED, DESTROYED } - + + private final AutoLock _lock = new AutoLock(); protected ContextStatus _contextStatus = ContextStatus.NOTSET; protected Context _scontext; private final AttributesMap _attributes; @@ -209,7 +204,6 @@ public enum ContextStatus private int _maxFormContentSize = Integer.getInteger(MAX_FORM_CONTENT_SIZE_KEY, DEFAULT_MAX_FORM_CONTENT_SIZE); private boolean _compactPath = false; private boolean _usingSecurityManager = System.getSecurityManager() != null; - private final List _programmaticListeners = new CopyOnWriteArrayList<>(); private final List _servletContextListeners = new CopyOnWriteArrayList<>(); private final List _destroyServletContextListeners = new ArrayList<>(); @@ -220,15 +214,13 @@ public enum ContextStatus private final Set _durableListeners = new HashSet<>(); private String[] _protectedTargets; private final CopyOnWriteArrayList _aliasChecks = new CopyOnWriteArrayList<>(); + private Availability _availability = Availability.UNAVAILABLE; public enum Availability { UNAVAILABLE, STARTING, AVAILABLE, SHUTDOWN, } - ; - private volatile Availability _availability = Availability.UNAVAILABLE; - public ContextHandler() { this(null, null, null); @@ -521,7 +513,7 @@ public Attributes getAttributes() */ public ClassLoader getClassLoader() { - return _classLoader; + return _lock.runLocked(() -> _classLoader); } /** @@ -532,9 +524,10 @@ public ClassLoader getClassLoader() @ManagedAttribute("The file classpath") public String getClassPath() { - if (_classLoader == null || !(_classLoader instanceof URLClassLoader)) + ClassLoader classLoader = getClassLoader(); + if (!(classLoader instanceof URLClassLoader)) return null; - URLClassLoader loader = (URLClassLoader)_classLoader; + URLClassLoader loader = (URLClassLoader)classLoader; URL[] urls = loader.getURLs(); StringBuilder classpath = new StringBuilder(); for (int i = 0; i < urls.length; i++) @@ -746,7 +739,7 @@ public CompletableFuture shutdown() */ public boolean isAvailable() { - return _availability == Availability.AVAILABLE; + return _lock.runLocked(() -> _availability == Availability.AVAILABLE); } /** @@ -756,7 +749,7 @@ public boolean isAvailable() */ public void setAvailable(boolean available) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (available && isRunning()) _availability = Availability.AVAILABLE; @@ -797,14 +790,15 @@ protected void doStart() throws Exception _durableListeners.addAll(getEventListeners()); + ClassLoader classLoader = getClassLoader(); try { // Set the classloader, context and enter scope - if (_classLoader != null) + if (classLoader != null) { currentThread = Thread.currentThread(); oldClassloader = currentThread.getContextClassLoader(); - currentThread.setContextClassLoader(_classLoader); + currentThread.setContextClassLoader(classLoader); } oldContext = __context.get(); __context.set(_scontext); @@ -825,7 +819,7 @@ protected void doStart() throws Exception exitScope(null); __context.set(oldContext); // reset the classloader - if (_classLoader != null && currentThread != null) + if (classLoader != null && currentThread != null) currentThread.setContextClassLoader(oldClassloader); } } @@ -1002,12 +996,13 @@ protected void doStop() throws Exception try { // Set the classloader - if (_classLoader != null) + ClassLoader classLoader = getClassLoader(); + if (classLoader != null) { - oldWebapploader = _classLoader; + oldWebapploader = classLoader; currentThread = Thread.currentThread(); oldClassloader = currentThread.getContextClassLoader(); - currentThread.setContextClassLoader(_classLoader); + currentThread.setContextClassLoader(classLoader); } stopContext(); @@ -1207,8 +1202,9 @@ else if (_contextPath.length() == 1) } } - if (_classLoader != null) - currentThread.setContextClassLoader(_classLoader); + ClassLoader classLoader = getClassLoader(); + if (classLoader != null) + currentThread.setContextClassLoader(classLoader); try { @@ -1233,7 +1229,7 @@ else if (_contextPath.length() == 1) exitScope(baseRequest); // reset the classloader - if (_classLoader != null) + if (classLoader != null) currentThread.setContextClassLoader(oldClassloader); // reset the context and servlet path. @@ -1360,8 +1356,6 @@ protected void exitScope(Request request) */ public void handle(Request request, Runnable runnable) { - ClassLoader oldClassloader = null; - Thread currentThread = null; Context oldContext = __context.get(); // Are we already in the scope? @@ -1372,16 +1366,18 @@ public void handle(Request request, Runnable runnable) } // Nope, so enter the scope and then exit + ClassLoader classLoader = getClassLoader(); + ClassLoader oldClassLoader = null; try { __context.set(_scontext); // Set the classloader - if (_classLoader != null) + if (classLoader != null) { - currentThread = Thread.currentThread(); - oldClassloader = currentThread.getContextClassLoader(); - currentThread.setContextClassLoader(_classLoader); + Thread currentThread = Thread.currentThread(); + oldClassLoader = currentThread.getContextClassLoader(); + currentThread.setContextClassLoader(classLoader); } enterScope(request, runnable); @@ -1392,10 +1388,8 @@ public void handle(Request request, Runnable runnable) exitScope(request); __context.set(oldContext); - if (oldClassloader != null) - { - currentThread.setContextClassLoader(oldClassloader); - } + if (classLoader != null) + Thread.currentThread().setContextClassLoader(oldClassLoader); } } @@ -1502,7 +1496,7 @@ public void clearAttributes() */ public void setClassLoader(ClassLoader classLoader) { - _classLoader = classLoader; + _lock.runLocked(() -> _classLoader = classLoader); } /** @@ -1783,15 +1777,16 @@ public String toString() return b.toString(); } - public synchronized Class loadClass(String className) throws ClassNotFoundException + public Class loadClass(String className) throws ClassNotFoundException { if (className == null) return null; - if (_classLoader == null) + ClassLoader classLoader = getClassLoader(); + if (classLoader == null) return Loader.loadClass(className); - return _classLoader.loadClass(className); + return classLoader.loadClass(className); } public void addLocaleEncoding(String locale, String encoding) @@ -2023,6 +2018,7 @@ public void clearAliasChecks() */ public class Context extends StaticContext { + private final AutoLock _lock = new AutoLock(); protected boolean _enabled = true; // whether or not the dynamic API is enabled for callers protected boolean _extendedListenerTypes = false; @@ -2260,70 +2256,79 @@ public Enumeration getInitParameterNames() } @Override - public synchronized Object getAttribute(String name) + public Object getAttribute(String name) { - Object o = ContextHandler.this.getAttribute(name); - if (o == null) - o = super.getAttribute(name); - return o; + try (AutoLock ignored = _lock.lock()) + { + Object o = ContextHandler.this.getAttribute(name); + if (o == null) + o = super.getAttribute(name); + return o; + } } @Override - public synchronized Enumeration getAttributeNames() + public Enumeration getAttributeNames() { - HashSet set = new HashSet<>(); - Enumeration e = super.getAttributeNames(); - while (e.hasMoreElements()) - { - set.add(e.nextElement()); - } - e = _attributes.getAttributeNames(); - while (e.hasMoreElements()) + try (AutoLock ignored = _lock.lock()) { - set.add(e.nextElement()); + HashSet set = new HashSet<>(); + Enumeration e = super.getAttributeNames(); + while (e.hasMoreElements()) + { + set.add(e.nextElement()); + } + e = ContextHandler.this.getAttributeNames(); + while (e.hasMoreElements()) + { + set.add(e.nextElement()); + } + return Collections.enumeration(set); } - - return Collections.enumeration(set); } @Override - public synchronized void setAttribute(String name, Object value) + public void setAttribute(String name, Object value) { - Object oldValue = super.getAttribute(name); - - if (value == null) - super.removeAttribute(name); - else - super.setAttribute(name, value); - - if (!_servletContextAttributeListeners.isEmpty()) + try (AutoLock ignored = _lock.lock()) { - ServletContextAttributeEvent event = new ServletContextAttributeEvent(_scontext, name, oldValue == null ? value : oldValue); + Object oldValue = super.getAttribute(name); + + if (value == null) + super.removeAttribute(name); + else + super.setAttribute(name, value); - for (ServletContextAttributeListener l : _servletContextAttributeListeners) + if (!_servletContextAttributeListeners.isEmpty()) { - if (oldValue == null) - l.attributeAdded(event); - else if (value == null) - l.attributeRemoved(event); - else - l.attributeReplaced(event); + ServletContextAttributeEvent event = new ServletContextAttributeEvent(_scontext, name, oldValue == null ? value : oldValue); + for (ServletContextAttributeListener l : _servletContextAttributeListeners) + { + if (oldValue == null) + l.attributeAdded(event); + else if (value == null) + l.attributeRemoved(event); + else + l.attributeReplaced(event); + } } } } @Override - public synchronized void removeAttribute(String name) + public void removeAttribute(String name) { - Object oldValue = super.getAttribute(name); - super.removeAttribute(name); - if (oldValue != null && !_servletContextAttributeListeners.isEmpty()) + try (AutoLock ignored = _lock.lock()) { - ServletContextAttributeEvent event = new ServletContextAttributeEvent(_scontext, name, oldValue); - - for (ServletContextAttributeListener l : _servletContextAttributeListeners) + Object oldValue = super.getAttribute(name); + super.removeAttribute(name); + if (oldValue != null && !_servletContextAttributeListeners.isEmpty()) { - l.attributeRemoved(event); + ServletContextAttributeEvent event = new ServletContextAttributeEvent(_scontext, name, oldValue); + for (ServletContextAttributeListener l : _servletContextAttributeListeners) + { + l.attributeRemoved(event); + } } } } @@ -2366,9 +2371,11 @@ public void addListener(String className) try { - @SuppressWarnings( - {"unchecked", "rawtypes"}) - Class clazz = _classLoader == null ? Loader.loadClass(className) : (Class)_classLoader.loadClass(className); + ClassLoader classLoader = ContextHandler.this.getClassLoader(); + @SuppressWarnings("unchecked") + Class clazz = classLoader == null + ? Loader.loadClass(className) + : (Class)classLoader.loadClass(className); addListener(clazz); } catch (ClassNotFoundException e) @@ -2438,10 +2445,12 @@ public ClassLoader getClassLoader() if (!_enabled) throw new UnsupportedOperationException(); + ClassLoader classLoader = ContextHandler.this.getClassLoader(); + // no security manager just return the classloader if (!isUsingSecurityManager()) { - return _classLoader; + return classLoader; } else { @@ -2454,13 +2463,13 @@ public ClassLoader getClassLoader() ClassLoader callerLoader = caller.getCallerClassLoader(2); while (callerLoader != null) { - if (callerLoader == _classLoader) - return _classLoader; + if (callerLoader == classLoader) + return classLoader; else callerLoader = callerLoader.getParent(); } System.getSecurityManager().checkPermission(new RuntimePermission("getClassLoader")); - return _classLoader; + return classLoader; } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java index 1d35b1ea63b0..1f76ee38da02 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java @@ -32,6 +32,7 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.ContainerLifeCycle; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -51,11 +52,10 @@ public class DefaultSessionIdManager extends ContainerLifeCycle implements SessionIdManager { private static final Logger LOG = LoggerFactory.getLogger(DefaultSessionIdManager.class); - public static final String __NEW_SESSION_ID = "org.eclipse.jetty.server.newSessionId"; - protected static final AtomicLong COUNTER = new AtomicLong(); + private final AutoLock _lock = new AutoLock(); protected Random _random; protected boolean _weakRandom; protected String _workerName; @@ -166,7 +166,7 @@ public Random getRandom() /** * @param random a random number generator for generating ids */ - public synchronized void setRandom(Random random) + public void setRandom(Random random) { _random = random; _weakRandom = false; @@ -229,7 +229,7 @@ public String newSessionId(long seedTerm) // pick a new unique ID! String id = null; - synchronized (_random) + try (AutoLock ignored = _lock.lock()) { while (id == null || id.length() == 0) { @@ -268,7 +268,7 @@ public String newSessionId(long seedTerm) if (!StringUtil.isBlank(_workerName)) id = _workerName + id; - id = id + Long.toString(COUNTER.getAndIncrement()); + id = id + COUNTER.getAndIncrement(); } } return id; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java index 3179e7771f51..d8626ed7eda8 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java @@ -24,6 +24,7 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.AbstractLifeCycle; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; import org.eclipse.jetty.util.thread.Scheduler; import org.slf4j.Logger; @@ -38,8 +39,9 @@ public class HouseKeeper extends AbstractLifeCycle { private static final Logger LOG = LoggerFactory.getLogger(HouseKeeper.class); - public static final long DEFAULT_PERIOD_MS = 1000L * 60 * 10; + + private final AutoLock _lock = new AutoLock(); protected SessionIdManager _sessionIdManager; protected Scheduler _scheduler; protected Scheduler.Task _task; //scavenge task @@ -125,7 +127,7 @@ else if (!_scheduler.isStarted()) */ protected void startScavenging() throws Exception { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_scheduler != null) { @@ -147,7 +149,7 @@ protected void startScavenging() throws Exception */ protected void stopScavenging() throws Exception { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_task != null) { @@ -168,7 +170,7 @@ protected void stopScavenging() throws Exception @Override protected void doStop() throws Exception { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { stopScavenging(); _scheduler = null; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java index 2ab519ca2b77..89f953108bf0 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java @@ -24,7 +24,6 @@ import java.util.Iterator; import java.util.Set; import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSessionActivationListener; @@ -93,8 +92,7 @@ public enum IdState protected State _state = State.VALID; // state of the session:valid,invalid // or being invalidated - protected AutoLock _lock = new AutoLock(); - protected Condition _stateChangeCompleted = _lock.newCondition(); + protected final AutoLock.WithCondition _lock = new AutoLock.WithCondition(); protected boolean _resident = false; protected final SessionInactivityTimer _sessionInactivityTimer; @@ -123,7 +121,7 @@ public void onTimeoutExpired() long now = System.currentTimeMillis(); //handle what to do with the session after the timer expired getSessionHandler().sessionInactivityTimerExpired(Session.this, now); - try (AutoLock lock = Session.this.lock()) + try (AutoLock ignored = Session.this.lock()) { //grab the lock and check what happened to the session: if it didn't get evicted and //it hasn't expired, we need to reset the timer @@ -208,10 +206,7 @@ public Session(SessionHandler handler, SessionData data) */ public long getRequests() { - try (AutoLock lock = _lock.lock()) - { - return _requests; - } + return _lock.runLocked(() -> _requests); } public void setExtendedId(String extendedId) @@ -221,15 +216,12 @@ public void setExtendedId(String extendedId) protected void cookieSet() { - try (AutoLock lock = _lock.lock()) - { - _sessionData.setCookieSet(_sessionData.getAccessed()); - } + _lock.runLocked(() -> _sessionData.setCookieSet(_sessionData.getAccessed())); } protected void use() { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { _requests++; @@ -242,7 +234,7 @@ protected void use() protected boolean access(long time) { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { if (!isValid() || !isResident()) return false; @@ -262,7 +254,7 @@ protected boolean access(long time) protected void complete() { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { _requests--; @@ -289,10 +281,7 @@ protected void complete() */ protected boolean isExpiredAt(long time) { - try (AutoLock lock = _lock.lock()) - { - return _sessionData.isExpiredAt(time); - } + return _lock.runLocked(() -> _sessionData.isExpiredAt(time)); } /** @@ -304,10 +293,7 @@ protected boolean isExpiredAt(long time) protected boolean isIdleLongerThan(int sec) { long now = System.currentTimeMillis(); - try (AutoLock lock = _lock.lock()) - { - return ((_sessionData.getAccessed() + (sec * 1000)) <= now); - } + return _lock.runLocked(() -> (_sessionData.getAccessed() + (sec * 1000)) <= now); } /** @@ -413,32 +399,23 @@ public void willPassivate() public boolean isValid() { - try (AutoLock lock = _lock.lock()) - { - return _state == State.VALID; - } + return _lock.runLocked(() -> _state == State.VALID); } public boolean isInvalid() { - try (AutoLock lock = _lock.lock()) - { - return _state == State.INVALID || _state == State.INVALIDATING; - } + return _lock.runLocked(() -> _state == State.INVALID || _state == State.INVALIDATING); } public long getCookieSetTime() { - try (AutoLock lock = _lock.lock()) - { - return _sessionData.getCookieSet(); - } + return _lock.runLocked(_sessionData::getCookieSet); } @Override public long getCreationTime() throws IllegalStateException { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { checkValidForRead(); return _sessionData.getCreated(); @@ -448,10 +425,7 @@ public long getCreationTime() throws IllegalStateException @Override public String getId() { - try (AutoLock lock = _lock.lock()) - { - return _sessionData.getId(); - } + return _lock.runLocked(_sessionData::getId); } public String getExtendedId() @@ -472,12 +446,10 @@ public String getVHost() @Override public long getLastAccessedTime() { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { if (isInvalid()) - { throw new IllegalStateException("Session not valid"); - } return _sessionData.getLastAccessed(); } } @@ -493,7 +465,7 @@ public ServletContext getServletContext() @Override public void setMaxInactiveInterval(int secs) { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { _sessionData.setMaxInactiveMs((long)secs * 1000L); _sessionData.calcAndSetExpiry(); @@ -526,7 +498,7 @@ public long calculateInactivityTimeout(long now) { long time = 0; - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { long remaining = _sessionData.getExpiry() - now; long maxInactive = _sessionData.getMaxInactiveMs(); @@ -587,7 +559,7 @@ else if (evictionPolicy == SessionCache.EVICT_ON_SESSION_EXIT) @Override public int getMaxInactiveInterval() { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { long maxInactiveMs = _sessionData.getMaxInactiveMs(); return (int)(maxInactiveMs < 0 ? -1 : maxInactiveMs / 1000); @@ -655,7 +627,7 @@ protected void checkValidForRead() throws IllegalStateException @Override public Object getAttribute(String name) { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { checkValidForRead(); return _sessionData.getAttribute(name); @@ -666,7 +638,7 @@ public Object getAttribute(String name) @Deprecated(since = "Servlet API 2.2") public Object getValue(String name) { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { checkValidForRead(); return _sessionData.getAttribute(name); @@ -676,7 +648,7 @@ public Object getValue(String name) @Override public Enumeration getAttributeNames() { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { checkValidForRead(); final Iterator itor = _sessionData.getKeys().iterator(); @@ -716,7 +688,7 @@ public Set getNames() @Deprecated(since = "Servlet API 2.2") public String[] getValueNames() throws IllegalStateException { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { checkValidForRead(); Iterator itor = _sessionData.getKeys().iterator(); @@ -735,7 +707,7 @@ public String[] getValueNames() throws IllegalStateException public void setAttribute(String name, Object value) { Object old = null; - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { // if session is not valid, don't accept the set checkValidForWrite(); @@ -779,7 +751,7 @@ public void renewId(HttpServletRequest request) String id = null; String extendedId = null; - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { while (true) { @@ -792,7 +764,7 @@ public void renewId(HttpServletRequest request) case CHANGING: try { - _stateChangeCompleted.await(); + lock.await(); } catch (InterruptedException e) { @@ -815,7 +787,7 @@ public void renewId(HttpServletRequest request) String newId = _handler._sessionIdManager.renewSessionId(id, extendedId, request); - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { switch (_state) { @@ -833,7 +805,7 @@ public void renewId(HttpServletRequest request) setIdChanged(true); _state = State.VALID; - _stateChangeCompleted.signalAll(); + lock.signalAll(); break; case INVALID: @@ -905,9 +877,8 @@ protected boolean beginInvalidate() { boolean result = false; - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { - while (true) { switch (_state) @@ -931,7 +902,7 @@ protected boolean beginInvalidate() { if (LOG.isDebugEnabled()) LOG.debug("Session {} waiting for id change to complete", _sessionData.getId()); - _stateChangeCompleted.await(); + lock.await(); } catch (InterruptedException e) { @@ -964,7 +935,7 @@ protected boolean beginInvalidate() */ protected void finishInvalidate() throws IllegalStateException { - try (AutoLock lock = _lock.lock()) + try (AutoLock.WithCondition lock = _lock.lock()) { try { @@ -994,7 +965,7 @@ protected void finishInvalidate() throws IllegalStateException // mark as invalid _state = State.INVALID; _handler.recordSessionTime(this); - _stateChangeCompleted.signalAll(); + lock.signalAll(); } } } @@ -1002,7 +973,7 @@ protected void finishInvalidate() throws IllegalStateException @Override public boolean isNew() throws IllegalStateException { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { checkValidForRead(); return _newSession; @@ -1011,18 +982,12 @@ public boolean isNew() throws IllegalStateException public void setIdChanged(boolean changed) { - try (AutoLock lock = _lock.lock()) - { - _idChanged = changed; - } + _lock.runLocked(() -> _idChanged = changed); } public boolean isIdChanged() { - try (AutoLock lock = _lock.lock()) - { - return _idChanged; - } + return _lock.runLocked(() -> _idChanged); } @Override @@ -1053,7 +1018,7 @@ public boolean isResident() @Override public String toString() { - try (AutoLock lock = _lock.lock()) + try (AutoLock ignored = _lock.lock()) { return String.format("%s@%x{id=%s,x=%s,req=%d,res=%b}", getClass().getSimpleName(), diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java index 98c91bd0694a..9e687844d6b8 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/SessionHandler.java @@ -399,6 +399,7 @@ protected void doStart() throws Exception _context = ContextHandler.getCurrentContext(); _loader = Thread.currentThread().getContextClassLoader(); + // Use a coarser lock to serialize concurrent start of many contexts. synchronized (server) { //Get a SessionDataStore and a SessionDataStore, falling back to in-memory sessions only diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java index 0ec2c4ae857d..0593da48421c 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java @@ -122,7 +122,7 @@ public void testIdleTimeoutAfterComplete() throws Exception }); } - private synchronized String process(String content) throws IOException, InterruptedException + private String process(String content) throws IOException, InterruptedException { String request = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n"; diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/BaseHolder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/BaseHolder.java index a365c7b93aa6..084c37aefa49 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/BaseHolder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/BaseHolder.java @@ -28,6 +28,7 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.component.Dumpable; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,6 +45,7 @@ public abstract class BaseHolder extends AbstractLifeCycle implements Dumpabl { private static final Logger LOG = LoggerFactory.getLogger(BaseHolder.class); + private final AutoLock _lock = new AutoLock(); private final Source _source; private Class _class; private String _className; @@ -60,6 +62,11 @@ public Source getSource() return _source; } + AutoLock lock() + { + return _lock.lock(); + } + /** * Do any setup necessary after starting * @@ -164,30 +171,36 @@ protected void illegalStateIfContextStarted() } } - protected synchronized void setInstance(T instance) + protected void setInstance(T instance) { - _instance = instance; - if (instance == null) - setHeldClass(null); - else - setHeldClass((Class)instance.getClass()); + try (AutoLock ignored = lock()) + { + _instance = instance; + if (instance == null) + setHeldClass(null); + else + setHeldClass((Class)instance.getClass()); + } } - protected synchronized T getInstance() + protected T getInstance() { - return _instance; + return _lock.runLocked(() -> _instance); } - protected synchronized T createInstance() throws Exception + protected T createInstance() throws Exception { - ServletContext ctx = getServletContext(); - if (ctx == null) - return getHeldClass().getDeclaredConstructor().newInstance(); + try (AutoLock ignored = lock()) + { + ServletContext ctx = getServletContext(); + if (ctx == null) + return getHeldClass().getDeclaredConstructor().newInstance(); - if (ServletContextHandler.Context.class.isAssignableFrom(ctx.getClass())) - return ((ServletContextHandler.Context)ctx).createInstance(this); + if (ServletContextHandler.Context.class.isAssignableFrom(ctx.getClass())) + return ((ServletContextHandler.Context)ctx).createInstance(this); - return null; + return null; + } } public ServletContext getServletContext() @@ -215,9 +228,9 @@ public ServletContext getServletContext() /** * @return True if this holder was created for a specific instance. */ - public synchronized boolean isInstance() + public boolean isInstance() { - return _instance != null; + return _lock.runLocked(() -> _instance != null); } @Override diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/FilterHolder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/FilterHolder.java index 515ef89f9bf7..044c3a2a6b67 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/FilterHolder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/FilterHolder.java @@ -34,6 +34,7 @@ import org.eclipse.jetty.util.TypeUtil; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.component.DumpableCollection; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -102,7 +103,7 @@ public void doStart() @Override public void initialize() throws Exception { - synchronized (this) + try (AutoLock ignored = lock()) { if (_filter != null) return; @@ -133,16 +134,19 @@ public void initialize() throws Exception } @Override - protected synchronized Filter createInstance() throws Exception + protected Filter createInstance() throws Exception { - Filter filter = super.createInstance(); - if (filter == null) + try (AutoLock ignored = lock()) { - ServletContext context = getServletContext(); - if (context != null) - filter = context.createFilter(getHeldClass()); + Filter filter = super.createInstance(); + if (filter == null) + { + ServletContext context = getServletContext(); + if (context != null) + filter = context.createFilter(getHeldClass()); + } + return filter; } - return filter; } @Override @@ -175,7 +179,7 @@ public void destroyInstance(Object o) getServletHandler().destroyFilter(f); } - public synchronized void setFilter(Filter filter) + public void setFilter(Filter filter) { setInstance(filter); } diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Holder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Holder.java index dfd1a9b4420a..b2afb37f8e0a 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Holder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Holder.java @@ -29,6 +29,7 @@ import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -98,11 +99,14 @@ public String getName() } @Override - protected synchronized void setInstance(T instance) + protected void setInstance(T instance) { - super.setInstance(instance); - if (getName() == null) - setName(String.format("%s@%x", instance.getClass().getName(), instance.hashCode())); + try (AutoLock ignored = lock()) + { + super.setInstance(instance); + if (getName() == null) + setName(String.format("%s@%x", instance.getClass().getName(), instance.hashCode())); + } } public void destroyInstance(Object instance) diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java index 17ae35dea144..47bb32fc5281 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java @@ -38,6 +38,7 @@ import org.eclipse.jetty.server.handler.HandlerWrapper; import org.eclipse.jetty.util.ArrayUtil; import org.eclipse.jetty.util.URIUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -163,7 +164,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) return; } - synchronized (_servletHandler) + try (AutoLock ignored = _servletHandler.lock()) { // find the entry for the invoker (me) _invokerEntry = _servletHandler.getMappedServlet(servletPath); @@ -175,7 +176,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) if (entry != null && !entry.equals(_invokerEntry)) { // Use the holder - holder = (ServletHolder)entry.getServletHolder(); + holder = entry.getServletHolder(); } else { diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ListenerHolder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ListenerHolder.java index 3259392743a7..754f9dba6a3e 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ListenerHolder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ListenerHolder.java @@ -23,6 +23,7 @@ import javax.servlet.ServletException; import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.util.thread.AutoLock; /** * ListenerHolder @@ -105,17 +106,19 @@ public void doStart() throws Exception } @Override - protected synchronized EventListener createInstance() throws Exception + protected EventListener createInstance() throws Exception { - - EventListener listener = super.createInstance(); - if (listener == null) + try (AutoLock ignored = lock()) { - ServletContext ctx = getServletContext(); - if (ctx != null) - listener = ctx.createListener(getHeldClass()); + EventListener listener = super.createInstance(); + if (listener == null) + { + ServletContext ctx = getServletContext(); + if (ctx != null) + listener = ctx.createListener(getHeldClass()); + } + return listener; } - return listener; } @Override diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java index 3206f4a0d1a7..5a6e63ed869c 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java @@ -69,6 +69,7 @@ import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.DumpableCollection; import org.eclipse.jetty.util.component.LifeCycle; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -80,7 +81,7 @@ *

* This handler does not implement the full J2EE features and is intended to * be used directly when a full web application is not required. If a Web application is required, - * then this handler should be used as part of a org.eclipse.jetty.webapp.WebAppContext. + * then this handler should be used as part of a {@code org.eclipse.jetty.webapp.WebAppContext}. *

* Unless run as part of a {@link ServletContextHandler} or derivative, the {@link #initialize()} * method must be called manually after start(). @@ -90,6 +91,7 @@ public class ServletHandler extends ScopedHandler { private static final Logger LOG = LoggerFactory.getLogger(ServletHandler.class); + private final AutoLock _lock = new AutoLock(); private ServletContextHandler _contextHandler; private ServletContext _servletContext; private FilterHolder[] _filters = new FilterHolder[0]; @@ -102,36 +104,29 @@ public class ServletHandler extends ScopedHandler private boolean _ensureDefaultServlet = true; private IdentityService _identityService; private boolean _allowDuplicateMappings = false; - private ServletHolder[] _servlets = new ServletHolder[0]; private ServletMapping[] _servletMappings; private final Map _filterNameMap = new HashMap<>(); private List _filterPathMappings; private MultiMap _filterNameMappings; - private final Map _servletNameMap = new HashMap<>(); private PathMappings _servletPathMap; - private ListenerHolder[] _listeners = new ListenerHolder[0]; private boolean _initialized = false; - @SuppressWarnings("unchecked") protected final ConcurrentMap[] _chainCache = new ConcurrentMap[FilterMapping.ALL]; - @SuppressWarnings("unchecked") protected final Queue[] _chainLRU = new Queue[FilterMapping.ALL]; - /** - * Constructor. - */ - public ServletHandler() + AutoLock lock() { + return _lock.lock(); } @Override public boolean isDumpable(Object o) { - return !(o instanceof Holder || o instanceof BaseHolder || o instanceof FilterMapping || o instanceof ServletMapping); + return !(o instanceof BaseHolder || o instanceof FilterMapping || o instanceof ServletMapping); } @Override @@ -146,8 +141,7 @@ public void dump(Appendable out, String indent) throws IOException } @Override - protected synchronized void doStart() - throws Exception + protected void doStart() throws Exception { ContextHandler.Context context = ContextHandler.getCurrentContext(); _servletContext = context == null ? new ContextHandler.StaticContext() : context; @@ -230,8 +224,7 @@ protected void stop(LifeCycle l) throws Exception } @Override - protected synchronized void doStop() - throws Exception + protected void doStop() throws Exception { super.doStop(); @@ -865,7 +858,7 @@ public void addServletWithMapping(ServletHolder servlet, String pathSpec) try { - synchronized (this) + try (AutoLock ignored = lock()) { if (servlet != null && !containsServletHolder(servlet)) setServlets(ArrayUtil.addToArray(holders, servlet, ServletHolder.class)); @@ -893,7 +886,7 @@ public void addServlet(ServletHolder holder) if (holder == null) return; - synchronized (this) + try (AutoLock ignored = lock()) { if (!containsServletHolder(holder)) setServlets(ArrayUtil.addToArray(getServlets(), holder, ServletHolder.class)); @@ -978,7 +971,7 @@ public void addFilterWithMapping(FilterHolder holder, String pathSpec, EnumSet(); - _filterNameMappings = new MultiMap<>(); - for (FilterMapping filtermapping : _filterMappings) + // update filter mappings + if (_filterMappings == null) + { + _filterPathMappings = null; + _filterNameMappings = null; + } + else { - FilterHolder filterHolder = _filterNameMap.get(filtermapping.getFilterName()); - if (filterHolder == null) - throw new IllegalStateException("No filter named " + filtermapping.getFilterName()); - filtermapping.setFilterHolder(filterHolder); - if (filtermapping.getPathSpecs() != null) - _filterPathMappings.add(filtermapping); - - if (filtermapping.getServletNames() != null) + _filterPathMappings = new ArrayList<>(); + _filterNameMappings = new MultiMap<>(); + for (FilterMapping filtermapping : _filterMappings) { - String[] names = filtermapping.getServletNames(); - for (String name : names) + FilterHolder filterHolder = _filterNameMap.get(filtermapping.getFilterName()); + if (filterHolder == null) + throw new IllegalStateException("No filter named " + filtermapping.getFilterName()); + filtermapping.setFilterHolder(filterHolder); + if (filtermapping.getPathSpecs() != null) + _filterPathMappings.add(filtermapping); + + if (filtermapping.getServletNames() != null) { - if (name != null) - _filterNameMappings.add(name, filtermapping); + String[] names = filtermapping.getServletNames(); + for (String name : names) + { + if (name != null) + _filterNameMappings.add(name, filtermapping); + } } } } - } - - // Map servlet paths to holders - if (_servletMappings == null) - { - _servletPathMap = null; - } - else - { - PathMappings pm = new PathMappings<>(); - //create a map of paths to set of ServletMappings that define that mapping - HashMap> sms = new HashMap<>(); - for (ServletMapping servletMapping : _servletMappings) + // Map servlet paths to holders + if (_servletMappings == null) { - String[] pathSpecs = servletMapping.getPathSpecs(); - if (pathSpecs != null) + _servletPathMap = null; + } + else + { + PathMappings pm = new PathMappings<>(); + + //create a map of paths to set of ServletMappings that define that mapping + HashMap> sms = new HashMap<>(); + for (ServletMapping servletMapping : _servletMappings) { - for (String pathSpec : pathSpecs) + String[] pathSpecs = servletMapping.getPathSpecs(); + if (pathSpecs != null) { - List mappings = sms.computeIfAbsent(pathSpec, k -> new ArrayList<>()); - mappings.add(servletMapping); + for (String pathSpec : pathSpecs) + { + List mappings = sms.computeIfAbsent(pathSpec, k -> new ArrayList<>()); + mappings.add(servletMapping); + } } } - } - - //evaluate path to servlet map based on servlet mappings - for (String pathSpec : sms.keySet()) - { - //for each path, look at the mappings where it is referenced - //if a mapping is for a servlet that is not enabled, skip it - List mappings = sms.get(pathSpec); - ServletMapping finalMapping = null; - for (ServletMapping mapping : mappings) + //evaluate path to servlet map based on servlet mappings + for (String pathSpec : sms.keySet()) { - //Get servlet associated with the mapping and check it is enabled - ServletHolder servletHolder = getServlet(mapping.getServletName()); - if (servletHolder == null) - throw new IllegalStateException("No such servlet: " + mapping.getServletName()); - //if the servlet related to the mapping is not enabled, skip it from consideration - if (!servletHolder.isEnabled()) - continue; - - //only accept a default mapping if we don't have any other - if (finalMapping == null) - finalMapping = mapping; - else + //for each path, look at the mappings where it is referenced + //if a mapping is for a servlet that is not enabled, skip it + List mappings = sms.get(pathSpec); + + ServletMapping finalMapping = null; + for (ServletMapping mapping : mappings) { - //already have a candidate - only accept another one - //if the candidate is a default, or we're allowing duplicate mappings - if (finalMapping.isFromDefaultDescriptor()) + //Get servlet associated with the mapping and check it is enabled + ServletHolder servletHolder = getServlet(mapping.getServletName()); + if (servletHolder == null) + throw new IllegalStateException("No such servlet: " + mapping.getServletName()); + //if the servlet related to the mapping is not enabled, skip it from consideration + if (!servletHolder.isEnabled()) + continue; + + //only accept a default mapping if we don't have any other + if (finalMapping == null) finalMapping = mapping; - else if (isAllowDuplicateMappings()) - { - LOG.warn("Multiple servlets map to path {}: {} and {}, choosing {}", pathSpec, finalMapping.getServletName(), mapping.getServletName(), mapping); - finalMapping = mapping; - } else { - //existing candidate isn't a default, if the one we're looking at isn't a default either, then its an error - if (!mapping.isFromDefaultDescriptor()) + //already have a candidate - only accept another one + //if the candidate is a default, or we're allowing duplicate mappings + if (finalMapping.isFromDefaultDescriptor()) + finalMapping = mapping; + else if (isAllowDuplicateMappings()) { - ServletHolder finalMappedServlet = getServlet(finalMapping.getServletName()); - throw new IllegalStateException("Multiple servlets map to path " + - pathSpec + ": " + - finalMappedServlet.getName() + "[mapped:" + finalMapping.getSource() + "]," + - mapping.getServletName() + "[mapped:" + mapping.getSource() + "]"); + LOG.warn("Multiple servlets map to path {}: {} and {}, choosing {}", pathSpec, finalMapping.getServletName(), mapping.getServletName(), mapping); + finalMapping = mapping; + } + else + { + //existing candidate isn't a default, if the one we're looking at isn't a default either, then its an error + if (!mapping.isFromDefaultDescriptor()) + { + ServletHolder finalMappedServlet = getServlet(finalMapping.getServletName()); + throw new IllegalStateException("Multiple servlets map to path " + + pathSpec + ": " + + finalMappedServlet.getName() + "[mapped:" + finalMapping.getSource() + "]," + + mapping.getServletName() + "[mapped:" + mapping.getSource() + "]"); + } } } } + if (finalMapping == null) + throw new IllegalStateException("No acceptable servlet mappings for " + pathSpec); + + if (LOG.isDebugEnabled()) + LOG.debug("Path={}[{}] mapped to servlet={}[{}]", + pathSpec, + finalMapping.getSource(), + finalMapping.getServletName(), + getServlet(finalMapping.getServletName()).getSource()); + + ServletPathSpec servletPathSpec = new ServletPathSpec(pathSpec); + MappedServlet mappedServlet = new MappedServlet(servletPathSpec, getServlet(finalMapping.getServletName())); + pm.put(servletPathSpec, mappedServlet); } - if (finalMapping == null) - throw new IllegalStateException("No acceptable servlet mappings for " + pathSpec); - if (LOG.isDebugEnabled()) - LOG.debug("Path={}[{}] mapped to servlet={}[{}]", - pathSpec, - finalMapping.getSource(), - finalMapping.getServletName(), - getServlet(finalMapping.getServletName()).getSource()); - - ServletPathSpec servletPathSpec = new ServletPathSpec(pathSpec); - MappedServlet mappedServlet = new MappedServlet(servletPathSpec, getServlet(finalMapping.getServletName())); - pm.put(servletPathSpec, mappedServlet); + _servletPathMap = pm; } - _servletPathMap = pm; - } - - // flush filter chain cache - for (int i = _chainCache.length; i-- > 0; ) - { - if (_chainCache[i] != null) - _chainCache[i].clear(); - } + // flush filter chain cache + for (int i = _chainCache.length; i-- > 0; ) + { + if (_chainCache[i] != null) + _chainCache[i].clear(); + } - if (LOG.isDebugEnabled()) - { - LOG.debug("filterNameMap=" + _filterNameMap); - LOG.debug("pathFilters=" + _filterPathMappings); - LOG.debug("servletFilterMap=" + _filterNameMappings); - LOG.debug("servletPathMap=" + _servletPathMap); - LOG.debug("servletNameMap=" + _servletNameMap); - } + if (LOG.isDebugEnabled()) + { + LOG.debug("filterNameMap=" + _filterNameMap); + LOG.debug("pathFilters=" + _filterPathMappings); + LOG.debug("servletFilterMap=" + _filterNameMappings); + LOG.debug("servletPathMap=" + _servletPathMap); + LOG.debug("servletNameMap=" + _servletNameMap); + } - try - { - if (_contextHandler != null && _contextHandler.isStarted() || _contextHandler == null && isStarted()) - initialize(); - } - catch (Exception e) - { - throw new RuntimeException(e); + try + { + if (_contextHandler != null && _contextHandler.isStarted() || _contextHandler == null && isStarted()) + initialize(); + } + catch (Exception e) + { + throw new RuntimeException(e); + } } } @@ -1426,30 +1425,36 @@ protected void notFound(Request baseRequest, HttpServletRequest request, HttpSer nextHandle(baseRequest.getPathInContext(), baseRequest, request, response); } - protected synchronized boolean containsFilterHolder(FilterHolder holder) + protected boolean containsFilterHolder(FilterHolder holder) { - if (_filters == null) - return false; - for (FilterHolder f : _filters) + try (AutoLock ignored = lock()) { - if (f == holder) - return true; + if (_filters == null) + return false; + for (FilterHolder f : _filters) + { + if (f == holder) + return true; + } + return false; } - return false; } - protected synchronized boolean containsServletHolder(ServletHolder holder) + protected boolean containsServletHolder(ServletHolder holder) { - if (_servlets == null) - return false; - for (ServletHolder s : _servlets) + try (AutoLock ignored = lock()) { - @SuppressWarnings("ReferenceEquality") - boolean foundServletHolder = (s == holder); - if (foundServletHolder) - return true; + if (_servlets == null) + return false; + for (ServletHolder s : _servlets) + { + @SuppressWarnings("ReferenceEquality") + boolean foundServletHolder = (s == holder); + if (foundServletHolder) + return true; + } + return false; } - return false; } /** @@ -1472,17 +1477,22 @@ public void setFilterMappings(FilterMapping[] filterMappings) invalidateChainsCache(); } - public synchronized void setFilters(FilterHolder[] holders) + public void setFilters(FilterHolder[] holders) { - if (holders != null) - for (FilterHolder holder : holders) + try (AutoLock ignored = lock()) + { + if (holders != null) { - holder.setServletHandler(this); + for (FilterHolder holder : holders) + { + holder.setServletHandler(this); + } } - updateBeans(_filters,holders); - _filters = holders; - updateNameMappings(); - invalidateChainsCache(); + updateBeans(_filters,holders); + _filters = holders; + updateNameMappings(); + invalidateChainsCache(); + } } /** @@ -1502,17 +1512,22 @@ public void setServletMappings(ServletMapping[] servletMappings) * * @param holders Array of servlets to define */ - public synchronized void setServlets(ServletHolder[] holders) + public void setServlets(ServletHolder[] holders) { - if (holders != null) - for (ServletHolder holder : holders) + try (AutoLock ignored = lock()) + { + if (holders != null) { - holder.setServletHandler(this); + for (ServletHolder holder : holders) + { + holder.setServletHandler(this); + } } - updateBeans(_servlets,holders); - _servlets = holders; - updateNameMappings(); - invalidateChainsCache(); + updateBeans(_servlets,holders); + _servlets = holders; + updateNameMappings(); + invalidateChainsCache(); + } } protected class CachedChain implements FilterChain diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHolder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHolder.java index 4e42bb6f0140..10e826058fa9 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHolder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHolder.java @@ -58,6 +58,7 @@ import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.component.DumpableCollection; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -172,11 +173,10 @@ public UnavailableException getUnavailableException() return null; } - public synchronized void setServlet(Servlet servlet) + public void setServlet(Servlet servlet) { if (servlet == null || servlet instanceof SingleThreadModel) throw new IllegalArgumentException(SingleThreadModel.class.getName() + " has been deprecated since Servlet API 2.4"); - setInstance(servlet); } @@ -254,11 +254,14 @@ public int hashCode() * @param name The role name as used by the servlet * @param link The role name as used by the container. */ - public synchronized void setUserRoleLink(String name, String link) + public void setUserRoleLink(String name, String link) { - if (_roleMap == null) - _roleMap = new HashMap<>(); - _roleMap.put(name, link); + try (AutoLock ignored = lock()) + { + if (_roleMap == null) + _roleMap = new HashMap<>(); + _roleMap.put(name, link); + } } /** @@ -270,10 +273,13 @@ public synchronized void setUserRoleLink(String name, String link) */ public String getUserRoleLink(String name) { - if (_roleMap == null) - return name; - String link = _roleMap.get(name); - return (link == null) ? name : link; + try (AutoLock ignored = lock()) + { + if (_roleMap == null) + return name; + String link = _roleMap.get(name); + return (link == null) ? name : link; + } } /** @@ -393,7 +399,7 @@ public void doStart() _config = new Config(); - synchronized (this) + try (AutoLock ignored = lock()) { if (getHeldClass() != null && javax.servlet.SingleThreadModel.class.isAssignableFrom(getHeldClass())) _servlet = new SingleThreadedWrapper(); @@ -404,7 +410,7 @@ public void doStart() public void initialize() throws Exception { - synchronized (this) + try (AutoLock ignored = lock()) { if (_servlet == null && (_initOnStartup || isInstance())) { @@ -418,7 +424,7 @@ public void initialize() public void doStop() throws Exception { - synchronized (this) + try (AutoLock ignored = lock()) { Servlet servlet = _servlet; if (servlet != null) @@ -464,7 +470,7 @@ public void destroyInstance(Object o) public Servlet getServlet() throws ServletException { - synchronized (this) + try (AutoLock ignored = lock()) { if (_servlet == null && isRunning()) { @@ -525,7 +531,7 @@ private void checkInitOnStartup() private Servlet makeUnavailable(UnavailableException e) { - synchronized (this) + try (AutoLock ignored = lock()) { _servlet = new UnavailableServlet(e, _servlet); return _servlet; @@ -553,10 +559,10 @@ private void makeUnavailable(final Throwable e) } } - private synchronized void initServlet() + private void initServlet() throws ServletException { - try + try (AutoLock ignored = lock()) { if (_servlet == null) _servlet = getInstance(); @@ -1010,12 +1016,12 @@ public ServletRegistration.Dynamic getRegistration() private class SingleThreadedWrapper implements Servlet { - Stack _stack = new Stack<>(); + private final Stack _stack = new Stack<>(); @Override public void destroy() { - synchronized (this) + try (AutoLock ignored = lock()) { while (_stack.size() > 0) { @@ -1047,7 +1053,7 @@ public String getServletInfo() @Override public void init(ServletConfig config) throws ServletException { - synchronized (this) + try (AutoLock ignored = lock()) { if (_stack.size() == 0) { @@ -1073,10 +1079,10 @@ public void init(ServletConfig config) throws ServletException public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { Servlet s; - synchronized (this) + try (AutoLock ignored = lock()) { if (_stack.size() > 0) - s = (Servlet)_stack.pop(); + s = _stack.pop(); else { try @@ -1101,7 +1107,7 @@ public void service(ServletRequest req, ServletResponse res) throws ServletExcep } finally { - synchronized (this) + try (AutoLock ignored = lock()) { _stack.push(s); } @@ -1123,16 +1129,19 @@ protected Servlet newInstance() throws Exception } @Override - protected synchronized Servlet createInstance() throws Exception + protected Servlet createInstance() throws Exception { - Servlet servlet = super.createInstance(); - if (servlet == null) + try (AutoLock ignored = lock()) { - ServletContext ctx = getServletContext(); - if (ctx != null) - servlet = ctx.createServlet(getHeldClass()); + Servlet servlet = super.createInstance(); + if (servlet == null) + { + ServletContext ctx = getServletContext(); + if (ctx != null) + servlet = ctx.createServlet(getHeldClass()); + } + return servlet; } - return servlet; } @Override @@ -1196,7 +1205,7 @@ else if (System.nanoTime() < _available) ((HttpServletResponse)res).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); else { - synchronized (ServletHolder.this) + try (AutoLock ignored = lock()) { ServletHolder.this._servlet = this._servlet; _servlet.service(req, res); diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/DoSFilter.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/DoSFilter.java index ab4b85a08696..ab11987faafd 100644 --- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/DoSFilter.java +++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/DoSFilter.java @@ -57,6 +57,7 @@ import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.annotation.ManagedOperation; import org.eclipse.jetty.util.annotation.Name; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; import org.eclipse.jetty.util.thread.Scheduler; import org.slf4j.Logger; @@ -1127,6 +1128,7 @@ static class RateTracker implements Runnable, HttpSessionBindingListener, HttpSe { private static final long serialVersionUID = 3534663738034577872L; + final AutoLock _lock = new AutoLock(); protected final String _filterName; protected transient ServletContext _context; protected final String _id; @@ -1152,7 +1154,7 @@ public RateTracker(ServletContext context, String filterName, String id, int typ public boolean isRateExceeded(long now) { final long last; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { last = _timestamps[_next]; _timestamps[_next] = now; @@ -1281,7 +1283,7 @@ public boolean isRateExceeded(long now) // rate limit is never exceeded, but we keep track of the request timestamps // so that we know whether there was recent activity on this tracker // and whether it should be expired - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _timestamps[_next] = now; _next = (_next + 1) % _timestamps.length; diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/EventSourceServlet.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/EventSourceServlet.java index 4506dbf592e3..376c7d5eeb32 100644 --- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/EventSourceServlet.java +++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/EventSourceServlet.java @@ -34,6 +34,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.eclipse.jetty.util.thread.AutoLock; + /** *

A servlet that implements the event source protocol, * also known as "server sent events".

@@ -42,11 +44,11 @@ * and to emit event source events.

*

This servlet supports the following configuration parameters:

*
    - *
  • heartBeatPeriod, that specifies the heartbeat period, in seconds, used to check + *
  • {@code heartBeatPeriod}, that specifies the heartbeat period, in seconds, used to check * whether the connection has been closed by the client; defaults to 10 seconds.
  • *
* - *

NOTE: there is currently no support for last-event-id.

+ *

NOTE: there is currently no support for {@code last-event-id}.

*/ public abstract class EventSourceServlet extends HttpServlet { @@ -77,7 +79,6 @@ public void destroy() @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - @SuppressWarnings("unchecked") Enumeration acceptValues = request.getHeaders("Accept"); while (acceptValues.hasMoreElements()) { @@ -127,6 +128,7 @@ protected void open(EventSource eventSource, EventSource.Emitter emitter) throws protected class EventSourceEmitter implements EventSource.Emitter, Runnable { + private final AutoLock lock = new AutoLock(); private final EventSource eventSource; private final AsyncContext async; private final ServletOutputStream output; @@ -143,7 +145,7 @@ public EventSourceEmitter(EventSource eventSource, AsyncContext async) throws IO @Override public void event(String name, String data) throws IOException { - synchronized (this) + try (AutoLock ignored = lock.lock()) { output.write(EVENT_FIELD); output.write(name.getBytes(StandardCharsets.UTF_8)); @@ -155,7 +157,7 @@ public void event(String name, String data) throws IOException @Override public void data(String data) throws IOException { - synchronized (this) + try (AutoLock ignored = lock.lock()) { BufferedReader reader = new BufferedReader(new StringReader(data)); String line; @@ -173,7 +175,7 @@ public void data(String data) throws IOException @Override public void comment(String comment) throws IOException { - synchronized (this) + try (AutoLock ignored = lock.lock()) { output.write(COMMENT_FIELD); output.write(comment.getBytes(StandardCharsets.UTF_8)); @@ -191,7 +193,7 @@ public void run() // on the second flush() try { - synchronized (this) + try (AutoLock ignored = lock.lock()) { output.write('\r'); flush(); @@ -217,7 +219,7 @@ protected void flush() throws IOException @Override public void close() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { closed = true; heartBeat.cancel(false); @@ -227,7 +229,7 @@ public void close() private void scheduleHeartBeat() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (!closed) heartBeat = scheduler.schedule(this, heartBeatPeriod, TimeUnit.SECONDS); diff --git a/jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONDateConvertor.java b/jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONDateConvertor.java index 02540fefa817..a3d63a0941d0 100644 --- a/jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONDateConvertor.java +++ b/jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONDateConvertor.java @@ -27,6 +27,7 @@ import org.eclipse.jetty.util.DateCache; import org.eclipse.jetty.util.ajax.JSON.Output; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,6 +41,7 @@ public class JSONDateConvertor implements JSON.Convertor { private static final Logger LOG = LoggerFactory.getLogger(JSONDateConvertor.class); + private final AutoLock _lock = new AutoLock(); private final boolean _fromJSON; private final DateCache _dateCache; private final SimpleDateFormat _format; @@ -77,7 +79,7 @@ public Object fromJSON(Map map) throw new UnsupportedOperationException(); try { - synchronized (_format) + try (AutoLock ignored = _lock.lock()) { return _format.parseObject((String)map.get("value")); } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java b/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java index 25cb183c8922..c91fd47915bb 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java @@ -32,6 +32,8 @@ import java.util.Timer; import java.util.TimerTask; +import org.eclipse.jetty.util.thread.AutoLock; + /** * RolloverFileOutputStream. * @@ -53,11 +55,11 @@ public class RolloverFileOutputStream extends OutputStream static final String ROLLOVER_FILE_BACKUP_FORMAT = "HHmmssSSS"; static final int ROLLOVER_FILE_RETAIN_DAYS = 31; + private final AutoLock _lock = new AutoLock(); private OutputStream _out; private RollTask _rollTask; private SimpleDateFormat _fileBackupFormat; private SimpleDateFormat _fileDateFormat; - private String _filename; private File _file; private boolean _append; @@ -176,11 +178,7 @@ public RolloverFileOutputStream(String filename, // Calculate Today's Midnight, based on Configured TimeZone (will be in past, even if by a few milliseconds) setFile(now); - synchronized (RolloverFileOutputStream.class) - { - if (__rollover == null) - __rollover = new Timer(RolloverFileOutputStream.class.getName(), true); - } + __rollover = new Timer(RolloverFileOutputStream.class.getName(), true); // This will schedule the rollover event to the next midnight scheduleNextRollover(now); @@ -205,10 +203,7 @@ private void scheduleNextRollover(ZonedDateTime now) // Schedule next rollover event to occur, based on local machine's Unix Epoch milliseconds long delay = midnight.toInstant().toEpochMilli() - now.toInstant().toEpochMilli(); - synchronized (RolloverFileOutputStream.class) - { - __rollover.schedule(_rollTask, delay); - } + __rollover.schedule(_rollTask, delay); } public String getFilename() @@ -234,7 +229,7 @@ void setFile(ZonedDateTime now) File oldFile = null; File newFile = null; File backupFile = null; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { // Check directory File file = new File(_filename); @@ -350,27 +345,25 @@ void removeOldFiles(ZonedDateTime now) @Override public void write(int b) throws IOException { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _out.write(b); } } @Override - public void write(byte[] buf) - throws IOException + public void write(byte[] buf) throws IOException { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _out.write(buf); } } @Override - public void write(byte[] buf, int off, int len) - throws IOException + public void write(byte[] buf, int off, int len) throws IOException { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _out.write(buf, off, len); } @@ -379,17 +372,16 @@ public void write(byte[] buf, int off, int len) @Override public void flush() throws IOException { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _out.flush(); } } @Override - public void close() - throws IOException + public void close() throws IOException { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { try { @@ -402,13 +394,9 @@ public void close() } } - synchronized (RolloverFileOutputStream.class) - { - if (_rollTask != null) - { - _rollTask.cancel(); - } - } + RollTask rollTask = _rollTask; + if (rollTask != null) + rollTask.cancel(); } private class RollTask extends TimerTask diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/Scanner.java b/jetty-util/src/main/java/org/eclipse/jetty/util/Scanner.java index 2ac15ca7b2c2..9a28572269e4 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/Scanner.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/Scanner.java @@ -43,6 +43,7 @@ import java.util.function.Predicate; import org.eclipse.jetty.util.component.AbstractLifeCycle; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -63,16 +64,17 @@ public class Scanner extends AbstractLifeCycle */ public static final int DEFAULT_SCAN_DEPTH = 1; public static final int MAX_SCAN_DEPTH = Integer.MAX_VALUE; - private static final Logger LOG = LoggerFactory.getLogger(Scanner.class); private static int __scannerId = 0; - private int _scanInterval; - private int _scanCount = 0; + + private final AutoLock _lock = new AutoLock(); private final List _listeners = new ArrayList<>(); private final Map _prevScan = new HashMap<>(); private final Map _currentScan = new HashMap<>(); - private FilenameFilter _filter; private final Map> _scannables = new HashMap<>(); + private int _scanInterval; + private int _scanCount = 0; + private FilenameFilter _filter; private volatile boolean _running = false; private boolean _reportExisting = true; private boolean _reportDirs = true; @@ -296,9 +298,9 @@ public Scanner() * * @return interval between scans in seconds */ - public synchronized int getScanInterval() + public int getScanInterval() { - return _scanInterval; + return _lock.runLocked(() -> _scanInterval); } /** @@ -306,10 +308,13 @@ public synchronized int getScanInterval() * * @param scanInterval pause between scans in seconds, or 0 for no scan after the initial scan. */ - public synchronized void setScanInterval(int scanInterval) + public void setScanInterval(int scanInterval) { - _scanInterval = scanInterval; - schedule(); + try (AutoLock ignored = _lock.lock()) + { + _scanInterval = scanInterval; + schedule(); + } } public void setScanDirs(List dirs) @@ -325,11 +330,11 @@ public void setScanDirs(List dirs) } @Deprecated - public synchronized void addScanDir(File dir) + public void addScanDir(File dir) { if (dir == null) return; - try + try (AutoLock ignored = _lock.lock()) { if (dir.isDirectory()) addDirectory(dir.toPath()); @@ -348,15 +353,14 @@ public synchronized void addScanDir(File dir) * @param p the Path of the file to scan. * @throws IOException */ - public synchronized void addFile(Path p) throws IOException + public void addFile(Path p) throws IOException { if (p == null) throw new IllegalStateException("Null path"); - File f = p.toFile(); if (!f.exists() || f.isDirectory()) throw new IllegalStateException("Not file or doesn't exist: " + f.getCanonicalPath()); - _scannables.put(p, null); + _lock.runLocked(() -> _scannables.put(p, null)); } /** @@ -366,24 +370,24 @@ public synchronized void addFile(Path p) throws IOException * @return an IncludeExcludeSet to which the caller can add PathMatcher patterns to match * @throws IOException */ - public synchronized IncludeExcludeSet addDirectory(Path p) - throws IOException + public IncludeExcludeSet addDirectory(Path p) throws IOException { if (p == null) throw new IllegalStateException("Null path"); - File f = p.toFile(); if (!f.exists() || !f.isDirectory()) throw new IllegalStateException("Not directory or doesn't exist: " + f.getCanonicalPath()); - - IncludeExcludeSet includesExcludes = _scannables.get(p); - if (includesExcludes == null) + + try (AutoLock ignored = _lock.lock()) { - includesExcludes = new IncludeExcludeSet<>(PathMatcherSet.class); - _scannables.put(p.toRealPath(), includesExcludes); + IncludeExcludeSet includesExcludes = _scannables.get(p); + if (includesExcludes == null) + { + includesExcludes = new IncludeExcludeSet<>(PathMatcherSet.class); + _scannables.put(p.toRealPath(), includesExcludes); + } + return includesExcludes; } - - return includesExcludes; } @Deprecated @@ -500,11 +504,11 @@ public boolean getReportDirs() * * @param listener the listener to add */ - public synchronized void addListener(Listener listener) + public void addListener(Listener listener) { if (listener == null) return; - _listeners.add(listener); + _lock.runLocked(() -> _listeners.add(listener)); } /** @@ -512,40 +516,43 @@ public synchronized void addListener(Listener listener) * * @param listener the Listener to be removed */ - public synchronized void removeListener(Listener listener) + public void removeListener(Listener listener) { if (listener == null) return; - _listeners.remove(listener); + _lock.runLocked(() -> _listeners.remove(listener)); } /** * Start the scanning action. */ @Override - public synchronized void doStart() + public void doStart() { - if (_running) - return; + try (AutoLock ignored = _lock.lock()) + { + if (_running) + return; - _running = true; - if (LOG.isDebugEnabled()) - LOG.debug("Scanner start: rprtExists={}, depth={}, rprtDirs={}, interval={}, filter={}, scannables={}", - _reportExisting, _scanDepth, _reportDirs, _scanInterval, _filter, _scannables); + _running = true; + if (LOG.isDebugEnabled()) + LOG.debug("Scanner start: rprtExists={}, depth={}, rprtDirs={}, interval={}, filter={}, scannables={}", + _reportExisting, _scanDepth, _reportDirs, _scanInterval, _filter, _scannables); - if (_reportExisting) - { - // if files exist at startup, report them - scan(); - scan(); // scan twice so files reported as stable - } - else - { - //just register the list of existing files and only report changes - scanFiles(); - _prevScan.putAll(_currentScan); + if (_reportExisting) + { + // if files exist at startup, report them + scan(); + scan(); // scan twice so files reported as stable + } + else + { + //just register the list of existing files and only report changes + scanFiles(); + _prevScan.putAll(_currentScan); + } + schedule(); } - schedule(); } public TimerTask newTimerTask() @@ -586,17 +593,20 @@ public void schedule() * Stop the scanning. */ @Override - public synchronized void doStop() + public void doStop() { - if (_running) + try (AutoLock ignored = _lock.lock()) { - _running = false; - if (_timer != null) - _timer.cancel(); - if (_task != null) - _task.cancel(); - _task = null; - _timer = null; + if (_running) + { + _running = false; + if (_timer != null) + _timer.cancel(); + if (_task != null) + _task.cancel(); + _task = null; + _timer = null; + } } } @@ -634,25 +644,28 @@ public boolean exists(String path) /** * Perform a pass of the scanner and report changes */ - public synchronized void scan() + public void scan() { - reportScanStart(++_scanCount); - scanFiles(); - reportDifferences(_currentScan, _prevScan); - _prevScan.clear(); - _prevScan.putAll(_currentScan); - reportScanEnd(_scanCount); - - for (Listener l : _listeners) + try (AutoLock ignored = _lock.lock()) { - try - { - if (l instanceof ScanListener) - ((ScanListener)l).scan(); - } - catch (Throwable e) + reportScanStart(++_scanCount); + scanFiles(); + reportDifferences(_currentScan, _prevScan); + _prevScan.clear(); + _prevScan.putAll(_currentScan); + reportScanEnd(_scanCount); + + for (Listener l : _listeners) { - LOG.warn("Unable to scan", e); + try + { + if (l instanceof ScanListener) + ((ScanListener)l).scan(); + } + catch (Throwable e) + { + LOG.warn("Unable to scan", e); + } } } } @@ -660,18 +673,21 @@ public synchronized void scan() /** * Scan all of the given paths. */ - public synchronized void scanFiles() + public void scanFiles() { - _currentScan.clear(); - for (Path p : _scannables.keySet()) + try (AutoLock ignored = _lock.lock()) { - try - { - Files.walkFileTree(p, EnumSet.allOf(FileVisitOption.class),_scanDepth, new Visitor(p, _scannables.get(p), _currentScan)); - } - catch (IOException e) + _currentScan.clear(); + for (Path p : _scannables.keySet()) { - LOG.warn("Error scanning files.", e); + try + { + Files.walkFileTree(p, EnumSet.allOf(FileVisitOption.class),_scanDepth, new Visitor(p, _scannables.get(p), _currentScan)); + } + catch (IOException e) + { + LOG.warn("Error scanning files.", e); + } } } } @@ -682,91 +698,94 @@ public synchronized void scanFiles() * @param currentScan the info from the most recent pass * @param oldScan info from the previous pass */ - private synchronized void reportDifferences(Map currentScan, Map oldScan) + private void reportDifferences(Map currentScan, Map oldScan) { - // scan the differences and add what was found to the map of notifications: - Set oldScanKeys = new HashSet<>(oldScan.keySet()); - - // Look for new and changed files - for (Map.Entry entry : currentScan.entrySet()) + try (AutoLock ignored = _lock.lock()) { - String file = entry.getKey(); - if (!oldScanKeys.contains(file)) + // scan the differences and add what was found to the map of notifications: + Set oldScanKeys = new HashSet<>(oldScan.keySet()); + + // Look for new and changed files + for (Entry entry : currentScan.entrySet()) { - Notification old = _notifications.put(file, Notification.ADDED); - if (old != null) + String file = entry.getKey(); + if (!oldScanKeys.contains(file)) { - switch (old) + Notification old = _notifications.put(file, Notification.ADDED); + if (old != null) { - case REMOVED: - case CHANGED: - _notifications.put(file, Notification.CHANGED); - break; - default: - break; + switch (old) + { + case REMOVED: + case CHANGED: + _notifications.put(file, Notification.CHANGED); + break; + default: + break; + } } } + else if (!oldScan.get(file).equals(currentScan.get(file))) + { + Notification old = _notifications.put(file, Notification.CHANGED); + if (old == Notification.ADDED) + _notifications.put(file, Notification.ADDED); + } } - else if (!oldScan.get(file).equals(currentScan.get(file))) - { - Notification old = _notifications.put(file, Notification.CHANGED); - if (old == Notification.ADDED) - _notifications.put(file, Notification.ADDED); - } - } - // Look for deleted files - for (String file : oldScan.keySet()) - { - if (!currentScan.containsKey(file)) + // Look for deleted files + for (String file : oldScan.keySet()) { - Notification old = _notifications.put(file, Notification.REMOVED); - if (old == Notification.ADDED) - _notifications.remove(file); + if (!currentScan.containsKey(file)) + { + Notification old = _notifications.put(file, Notification.REMOVED); + if (old == Notification.ADDED) + _notifications.remove(file); + } } - } - if (LOG.isDebugEnabled()) - LOG.debug("scanned " + _scannables.keySet() + ": " + _notifications); + if (LOG.isDebugEnabled()) + LOG.debug("scanned " + _scannables.keySet() + ": " + _notifications); - // Process notifications - // Only process notifications that are for stable files (ie same in old and current scan). - List bulkChanges = new ArrayList<>(); - for (Iterator> iter = _notifications.entrySet().iterator(); iter.hasNext(); ) - { - - Entry entry = iter.next(); - String file = entry.getKey(); - // Is the file stable? - if (oldScan.containsKey(file)) + // Process notifications + // Only process notifications that are for stable files (ie same in old and current scan). + List bulkChanges = new ArrayList<>(); + for (Iterator> iter = _notifications.entrySet().iterator(); iter.hasNext(); ) { - if (!oldScan.get(file).equals(currentScan.get(file))) + + Entry entry = iter.next(); + String file = entry.getKey(); + // Is the file stable? + if (oldScan.containsKey(file)) + { + if (!oldScan.get(file).equals(currentScan.get(file))) + continue; + } + else if (currentScan.containsKey(file)) continue; + + // File is stable so notify + Notification notification = entry.getValue(); + iter.remove(); + bulkChanges.add(file); + switch (notification) + { + case ADDED: + reportAddition(file); + break; + case CHANGED: + reportChange(file); + break; + case REMOVED: + reportRemoval(file); + break; + default: + break; + } } - else if (currentScan.containsKey(file)) - continue; - - // File is stable so notify - Notification notification = entry.getValue(); - iter.remove(); - bulkChanges.add(file); - switch (notification) - { - case ADDED: - reportAddition(file); - break; - case CHANGED: - reportChange(file); - break; - case REMOVED: - reportRemoval(file); - break; - default: - break; - } + if (!bulkChanges.isEmpty()) + reportBulkChanges(bulkChanges); } - if (!bulkChanges.isEmpty()) - reportBulkChanges(bulkChanges); } private void warn(Object listener, String filename, Throwable th) diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java b/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java index 77aebf337794..9b08454e42f7 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java @@ -376,15 +376,12 @@ public static void append(StringBuilder buf, int offset, int length) { - synchronized (buf) + int end = offset + length; + for (int i = offset; i < end; i++) { - int end = offset + length; - for (int i = offset; i < end; i++) - { - if (i >= s.length()) - break; - buf.append(s.charAt(i)); - } + if (i >= s.length()) + break; + buf.append(s.charAt(i)); } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/URIUtil.java b/jetty-util/src/main/java/org/eclipse/jetty/util/URIUtil.java index c7c88b09b673..fa381aa9dbc2 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/URIUtil.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/URIUtil.java @@ -1180,27 +1180,24 @@ public static void appendSchemeHostPort(StringBuilder url, String scheme, String */ public static void appendSchemeHostPort(StringBuffer url, String scheme, String server, int port) { - synchronized (url) - { - url.append(scheme).append("://").append(HostPort.normalizeHost(server)); + url.append(scheme).append("://").append(HostPort.normalizeHost(server)); - if (port > 0) + if (port > 0) + { + switch (scheme) { - switch (scheme) - { - case "http": - if (port != 80) - url.append(':').append(port); - break; - - case "https": - if (port != 443) - url.append(':').append(port); - break; + case "http": + if (port != 80) + url.append(':').append(port); + break; - default: + case "https": + if (port != 443) url.append(':').append(port); - } + break; + + default: + url.append(':').append(port); } } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java b/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java index 32ff9592f672..906d72ee8f3e 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java @@ -140,7 +140,7 @@ public String encode(Charset charset) * for parameters without a value. e.g. "blah?a=&b=&c=". * @return the MultiMap as a string encoded with % encodings */ - public synchronized String encode(Charset charset, boolean equalsForNullValue) + public String encode(Charset charset, boolean equalsForNullValue) { return encode(this, charset, equalsForNullValue); } @@ -238,64 +238,61 @@ public static void decodeTo(String content, MultiMap map, Charset charse return; } - synchronized (map) + String key = null; + String value; + int mark = -1; + boolean encoded = false; + for (int i = 0; i < content.length(); i++) { - String key = null; - String value; - int mark = -1; - boolean encoded = false; - for (int i = 0; i < content.length(); i++) + char c = content.charAt(i); + switch (c) { - char c = content.charAt(i); - switch (c) - { - case '&': - int l = i - mark - 1; - value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l, charset) : content.substring(mark + 1, i)); - mark = i; - encoded = false; - if (key != null) - { - map.add(key, value); - } - else if (value != null && value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - break; - case '=': - if (key != null) - break; - key = encoded ? decodeString(content, mark + 1, i - mark - 1, charset) : content.substring(mark + 1, i); - mark = i; - encoded = false; - break; - case '+': - encoded = true; - break; - case '%': - encoded = true; + case '&': + int l = i - mark - 1; + value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l, charset) : content.substring(mark + 1, i)); + mark = i; + encoded = false; + if (key != null) + { + map.add(key, value); + } + else if (value != null && value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + break; + case '=': + if (key != null) break; - } + key = encoded ? decodeString(content, mark + 1, i - mark - 1, charset) : content.substring(mark + 1, i); + mark = i; + encoded = false; + break; + case '+': + encoded = true; + break; + case '%': + encoded = true; + break; } + } - if (key != null) - { - int l = content.length() - mark - 1; - value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l, charset) : content.substring(mark + 1)); - map.add(key, value); - } - else if (mark < content.length()) + if (key != null) + { + int l = content.length() - mark - 1; + value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l, charset) : content.substring(mark + 1)); + map.add(key, value); + } + else if (mark < content.length()) + { + key = encoded + ? decodeString(content, mark + 1, content.length() - mark - 1, charset) + : content.substring(mark + 1); + if (key != null && key.length() > 0) { - key = encoded - ? decodeString(content, mark + 1, content.length() - mark - 1, charset) - : content.substring(mark + 1); - if (key != null && key.length() > 0) - { - map.add(key, ""); - } + map.add(key, ""); } } } @@ -316,75 +313,72 @@ public static void decodeUtf8To(String query, MultiMap map) public static void decodeUtf8To(String query, int offset, int length, MultiMap map) { Utf8StringBuilder buffer = new Utf8StringBuilder(); - synchronized (map) - { - String key = null; - String value = null; + String key = null; + String value = null; - int end = offset + length; - for (int i = offset; i < end; i++) + int end = offset + length; + for (int i = offset; i < end; i++) + { + char c = query.charAt(i); + switch (c) { - char c = query.charAt(i); - switch (c) - { - case '&': - value = buffer.toReplacedString(); - buffer.reset(); - if (key != null) - { - map.add(key, value); - } - else if (value != null && value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - break; + case '&': + value = buffer.toReplacedString(); + buffer.reset(); + if (key != null) + { + map.add(key, value); + } + else if (value != null && value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + break; - case '=': - if (key != null) - { - buffer.append(c); - break; - } - key = buffer.toReplacedString(); - buffer.reset(); + case '=': + if (key != null) + { + buffer.append(c); break; + } + key = buffer.toReplacedString(); + buffer.reset(); + break; - case '+': - buffer.append((byte)' '); - break; + case '+': + buffer.append((byte)' '); + break; - case '%': - if (i + 2 < end) - { - char hi = query.charAt(++i); - char lo = query.charAt(++i); - buffer.append(decodeHexByte(hi, lo)); - } - else - { - throw new Utf8Appendable.NotUtf8Exception("Incomplete % encoding"); - } - break; + case '%': + if (i + 2 < end) + { + char hi = query.charAt(++i); + char lo = query.charAt(++i); + buffer.append(decodeHexByte(hi, lo)); + } + else + { + throw new Utf8Appendable.NotUtf8Exception("Incomplete % encoding"); + } + break; - default: - buffer.append(c); - break; - } + default: + buffer.append(c); + break; } + } - if (key != null) - { - value = buffer.toReplacedString(); - buffer.reset(); - map.add(key, value); - } - else if (buffer.length() > 0) - { - map.add(buffer.toReplacedString(), ""); - } + if (key != null) + { + value = buffer.toReplacedString(); + buffer.reset(); + map.add(key, value); + } + else if (buffer.length() > 0) + { + map.add(buffer.toReplacedString(), ""); } } @@ -400,74 +394,71 @@ else if (buffer.length() > 0) public static void decode88591To(InputStream in, MultiMap map, int maxLength, int maxKeys) throws IOException { - synchronized (map) - { - StringBuilder buffer = new StringBuilder(); - String key = null; - String value = null; + StringBuilder buffer = new StringBuilder(); + String key = null; + String value = null; - int b; + int b; - int totalLength = 0; - while ((b = in.read()) >= 0) + int totalLength = 0; + while ((b = in.read()) >= 0) + { + switch ((char)b) { - switch ((char)b) - { - case '&': - value = buffer.length() == 0 ? "" : buffer.toString(); - buffer.setLength(0); - if (key != null) - { - map.add(key, value); - } - else if (value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - checkMaxKeys(map, maxKeys); - break; + case '&': + value = buffer.length() == 0 ? "" : buffer.toString(); + buffer.setLength(0); + if (key != null) + { + map.add(key, value); + } + else if (value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + checkMaxKeys(map, maxKeys); + break; - case '=': - if (key != null) - { - buffer.append((char)b); - break; - } - key = buffer.toString(); - buffer.setLength(0); + case '=': + if (key != null) + { + buffer.append((char)b); break; + } + key = buffer.toString(); + buffer.setLength(0); + break; - case '+': - buffer.append(' '); - break; + case '+': + buffer.append(' '); + break; - case '%': - int code0 = in.read(); - int code1 = in.read(); - buffer.append(decodeHexChar(code0, code1)); - break; + case '%': + int code0 = in.read(); + int code1 = in.read(); + buffer.append(decodeHexChar(code0, code1)); + break; - default: - buffer.append((char)b); - break; - } - checkMaxLength(++totalLength, maxLength); + default: + buffer.append((char)b); + break; } + checkMaxLength(++totalLength, maxLength); + } - if (key != null) - { - value = buffer.length() == 0 ? "" : buffer.toString(); - buffer.setLength(0); - map.add(key, value); - } - else if (buffer.length() > 0) - { - map.add(buffer.toString(), ""); - } - checkMaxKeys(map, maxKeys); + if (key != null) + { + value = buffer.length() == 0 ? "" : buffer.toString(); + buffer.setLength(0); + map.add(key, value); } + else if (buffer.length() > 0) + { + map.add(buffer.toString(), ""); + } + checkMaxKeys(map, maxKeys); } /** @@ -482,74 +473,71 @@ else if (buffer.length() > 0) public static void decodeUtf8To(InputStream in, MultiMap map, int maxLength, int maxKeys) throws IOException { - synchronized (map) - { - Utf8StringBuilder buffer = new Utf8StringBuilder(); - String key = null; - String value = null; + Utf8StringBuilder buffer = new Utf8StringBuilder(); + String key = null; + String value = null; - int b; + int b; - int totalLength = 0; - while ((b = in.read()) >= 0) + int totalLength = 0; + while ((b = in.read()) >= 0) + { + switch ((char)b) { - switch ((char)b) - { - case '&': - value = buffer.toReplacedString(); - buffer.reset(); - if (key != null) - { - map.add(key, value); - } - else if (value != null && value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - checkMaxKeys(map, maxKeys); - break; - - case '=': - if (key != null) - { - buffer.append((byte)b); - break; - } - key = buffer.toReplacedString(); - buffer.reset(); - break; - - case '+': - buffer.append((byte)' '); - break; - - case '%': - char code0 = (char)in.read(); - char code1 = (char)in.read(); - buffer.append(decodeHexByte(code0, code1)); - break; + case '&': + value = buffer.toReplacedString(); + buffer.reset(); + if (key != null) + { + map.add(key, value); + } + else if (value != null && value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + checkMaxKeys(map, maxKeys); + break; - default: + case '=': + if (key != null) + { buffer.append((byte)b); break; - } - checkMaxLength(++totalLength, maxLength); + } + key = buffer.toReplacedString(); + buffer.reset(); + break; + + case '+': + buffer.append((byte)' '); + break; + + case '%': + char code0 = (char)in.read(); + char code1 = (char)in.read(); + buffer.append(decodeHexByte(code0, code1)); + break; + + default: + buffer.append((byte)b); + break; } + checkMaxLength(++totalLength, maxLength); + } - if (key != null) - { - value = buffer.toReplacedString(); - buffer.reset(); - map.add(key, value); - } - else if (buffer.length() > 0) - { - map.add(buffer.toReplacedString(), ""); - } - checkMaxKeys(map, maxKeys); + if (key != null) + { + value = buffer.toReplacedString(); + buffer.reset(); + map.add(key, value); + } + else if (buffer.length() > 0) + { + map.add(buffer.toReplacedString(), ""); } + checkMaxKeys(map, maxKeys); } public static void decodeUtf16To(InputStream in, MultiMap map, int maxLength, int maxKeys) throws IOException @@ -627,77 +615,74 @@ public static void decodeTo(InputStream in, MultiMap map, Charset charse return; } - synchronized (map) - { - String key = null; - String value = null; + String key = null; + String value = null; - int c; + int c; - int totalLength = 0; + int totalLength = 0; - try (ByteArrayOutputStream2 output = new ByteArrayOutputStream2()) - { - int size = 0; + try (ByteArrayOutputStream2 output = new ByteArrayOutputStream2()) + { + int size = 0; - while ((c = in.read()) > 0) + while ((c = in.read()) > 0) + { + switch ((char)c) { - switch ((char)c) - { - case '&': - size = output.size(); - value = size == 0 ? "" : output.toString(charset); - output.setCount(0); - if (key != null) - { - map.add(key, value); - } - else if (value != null && value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - checkMaxKeys(map, maxKeys); - break; - case '=': - if (key != null) - { - output.write(c); - break; - } - size = output.size(); - key = size == 0 ? "" : output.toString(charset); - output.setCount(0); - break; - case '+': - output.write(' '); - break; - case '%': - int code0 = in.read(); - int code1 = in.read(); - output.write(decodeHexChar(code0, code1)); - break; - default: + case '&': + size = output.size(); + value = size == 0 ? "" : output.toString(charset); + output.setCount(0); + if (key != null) + { + map.add(key, value); + } + else if (value != null && value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + checkMaxKeys(map, maxKeys); + break; + case '=': + if (key != null) + { output.write(c); break; - } - checkMaxLength(++totalLength, maxLength); + } + size = output.size(); + key = size == 0 ? "" : output.toString(charset); + output.setCount(0); + break; + case '+': + output.write(' '); + break; + case '%': + int code0 = in.read(); + int code1 = in.read(); + output.write(decodeHexChar(code0, code1)); + break; + default: + output.write(c); + break; } + checkMaxLength(++totalLength, maxLength); + } - size = output.size(); - if (key != null) - { - value = size == 0 ? "" : output.toString(charset); - output.setCount(0); - map.add(key, value); - } - else if (size > 0) - { - map.add(output.toString(charset), ""); - } - checkMaxKeys(map, maxKeys); + size = output.size(); + if (key != null) + { + value = size == 0 ? "" : output.toString(charset); + output.setCount(0); + map.add(key, value); } + else if (size > 0) + { + map.add(output.toString(charset), ""); + } + checkMaxKeys(map, maxKeys); } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/component/AbstractLifeCycle.java b/jetty-util/src/main/java/org/eclipse/jetty/util/component/AbstractLifeCycle.java index 8925683b1286..ccc7d68c48b6 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/component/AbstractLifeCycle.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/component/AbstractLifeCycle.java @@ -26,6 +26,7 @@ import org.eclipse.jetty.util.Uptime; import org.eclipse.jetty.util.annotation.ManagedAttribute; import org.eclipse.jetty.util.annotation.ManagedObject; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,7 +54,7 @@ enum State public static final String STOPPING = State.STOPPING.toString(); private final List _eventListener = new CopyOnWriteArrayList<>(); - private final Object _lock = new Object(); + private final AutoLock _lock = new AutoLock(); private volatile State _state = State.STOPPED; /** @@ -76,7 +77,7 @@ protected void doStop() throws Exception @Override public final void start() throws Exception { - synchronized (_lock) + try (AutoLock ignored = _lock.lock()) { try { @@ -117,7 +118,7 @@ public final void start() throws Exception @Override public final void stop() throws Exception { - synchronized (_lock) + try (AutoLock ignored = _lock.lock()) { try { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/component/AttributeContainerMap.java b/jetty-util/src/main/java/org/eclipse/jetty/util/component/AttributeContainerMap.java index 22749d30972e..f6165e9bc325 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/component/AttributeContainerMap.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/component/AttributeContainerMap.java @@ -26,52 +26,63 @@ import java.util.Set; import org.eclipse.jetty.util.Attributes; +import org.eclipse.jetty.util.thread.AutoLock; /** * An Attributes implementation that holds it's values in an immutable {@link ContainerLifeCycle} */ public class AttributeContainerMap extends ContainerLifeCycle implements Attributes { + private final AutoLock _lock = new AutoLock(); private final Map _map = new HashMap<>(); @Override - public synchronized void setAttribute(String name, Object attribute) + public void setAttribute(String name, Object attribute) { - Object old = _map.put(name, attribute); - updateBean(old, attribute); + try (AutoLock ignored = _lock.lock()) + { + Object old = _map.put(name, attribute); + updateBean(old, attribute); + } } @Override - public synchronized void removeAttribute(String name) + public void removeAttribute(String name) { - Object removed = _map.remove(name); - if (removed != null) - removeBean(removed); + try (AutoLock ignored = _lock.lock()) + { + Object removed = _map.remove(name); + if (removed != null) + removeBean(removed); + } } @Override - public synchronized Object getAttribute(String name) + public Object getAttribute(String name) { - return _map.get(name); + return _lock.runLocked(() -> _map.get(name)); } @Override - public synchronized Enumeration getAttributeNames() + public Enumeration getAttributeNames() { - return Collections.enumeration(_map.keySet()); + return _lock.runLocked(() -> Collections.enumeration(getAttributeNameSet())); } @Override public Set getAttributeNameSet() { - return _map.keySet(); + return _lock.runLocked(_map::keySet); } @Override - public synchronized void clearAttributes() + public void clearAttributes() { - _map.clear(); - this.removeBeans(); + try (AutoLock ignored = _lock.lock()) + { + _map.clear(); + this.removeBeans(); + } } @Override diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarFileResource.java b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarFileResource.java index ef488981ff8e..c18494668207 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarFileResource.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarFileResource.java @@ -30,12 +30,14 @@ import java.util.jar.JarFile; import org.eclipse.jetty.util.URIUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JarFileResource extends JarResource { private static final Logger LOG = LoggerFactory.getLogger(JarFileResource.class); + private JarFile _jarFile; private File _file; private String[] _list; @@ -51,73 +53,81 @@ protected JarFileResource(URL url, boolean useCaches) } @Override - public synchronized void close() + public void close() { - _exists = false; - _list = null; - _entry = null; - _file = null; - //if the jvm is not doing url caching, then the JarFiles will not be cached either, - //and so they are safe to close - if (!getUseCaches()) + try (AutoLock ignored = _lock.lock()) { - if (_jarFile != null) + _exists = false; + _list = null; + _entry = null; + _file = null; + //if the jvm is not doing url caching, then the JarFiles will not be cached either, + //and so they are safe to close + if (!getUseCaches()) { - try - { - if (LOG.isDebugEnabled()) - LOG.debug("Closing JarFile " + _jarFile.getName()); - _jarFile.close(); - } - catch (IOException ioe) + if (_jarFile != null) { - LOG.trace("IGNORED", ioe); + try + { + if (LOG.isDebugEnabled()) + LOG.debug("Closing JarFile " + _jarFile.getName()); + _jarFile.close(); + } + catch (IOException ioe) + { + LOG.trace("IGNORED", ioe); + } } } + _jarFile = null; + super.close(); } - _jarFile = null; - super.close(); } @Override - protected synchronized boolean checkConnection() + protected boolean checkConnection() { - try - { - super.checkConnection(); - } - finally + try (AutoLock ignored = _lock.lock()) { - if (_jarConnection == null) + try { - _entry = null; - _file = null; - _jarFile = null; - _list = null; + super.checkConnection(); + } + finally + { + if (_jarConnection == null) + { + _entry = null; + _file = null; + _jarFile = null; + _list = null; + } } + return _jarFile != null; } - return _jarFile != null; } @Override - protected synchronized void newConnection() - throws IOException + protected void newConnection() throws IOException { - super.newConnection(); - - _entry = null; - _file = null; - _jarFile = null; - _list = null; - - // Work with encoded URL path (_urlString is assumed to be encoded) - int sep = _urlString.lastIndexOf("!/"); - _jarUrl = _urlString.substring(0, sep + 2); - _path = URIUtil.decodePath(_urlString.substring(sep + 2)); - if (_path.length() == 0) - _path = null; - _jarFile = _jarConnection.getJarFile(); - _file = new File(_jarFile.getName()); + try (AutoLock ignored = _lock.lock()) + { + super.newConnection(); + + _entry = null; + _file = null; + _jarFile = null; + _list = null; + + // Work with encoded URL path (_urlString is assumed to be encoded) + int sep = _urlString.lastIndexOf("!/"); + _jarUrl = _urlString.substring(0, sep + 2); + _path = URIUtil.decodePath(_urlString.substring(sep + 2)); + if (_path.length() == 0) + _path = null; + _jarFile = _jarConnection.getJarFile(); + _file = new File(_jarFile.getName()); + } } /** @@ -253,36 +263,39 @@ public long lastModified() } @Override - public synchronized String[] list() + public String[] list() { - if (isDirectory() && _list == null) + try (AutoLock ignored = _lock.lock()) { - List list = null; - try - { - list = listEntries(); - } - catch (Exception e) + if (isDirectory() && _list == null) { - //Sun's JarURLConnection impl for jar: protocol will close a JarFile in its connect() method if - //useCaches == false (eg someone called URLConnection with defaultUseCaches==true). - //As their sun.net.www.protocol.jar package caches JarFiles and/or connections, we can wind up in - //the situation where the JarFile we have remembered in our _jarFile member has actually been closed - //by other code. - //So, do one retry to drop a connection and get a fresh JarFile - LOG.warn("Retrying list:" + e); - LOG.debug("JarFile list failure", e); - close(); - list = listEntries(); - } + List list = null; + try + { + list = listEntries(); + } + catch (Exception e) + { + //Sun's JarURLConnection impl for jar: protocol will close a JarFile in its connect() method if + //useCaches == false (eg someone called URLConnection with defaultUseCaches==true). + //As their sun.net.www.protocol.jar package caches JarFiles and/or connections, we can wind up in + //the situation where the JarFile we have remembered in our _jarFile member has actually been closed + //by other code. + //So, do one retry to drop a connection and get a fresh JarFile + LOG.warn("Retrying list:" + e); + LOG.debug("JarFile list failure", e); + close(); + list = listEntries(); + } - if (list != null) - { - _list = new String[list.size()]; - list.toArray(_list); + if (list != null) + { + _list = new String[list.size()]; + list.toArray(_list); + } } + return _list; } - return _list; } private List listEntries() diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java index ec7e925aec38..276df113b374 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java @@ -34,12 +34,14 @@ import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.URIUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JarResource extends URLResource { private static final Logger LOG = LoggerFactory.getLogger(JarResource.class); + protected JarURLConnection _jarConnection; protected JarResource(URL url) @@ -53,28 +55,34 @@ protected JarResource(URL url, boolean useCaches) } @Override - public synchronized void close() + public void close() { - _jarConnection = null; - super.close(); + try (AutoLock ignored = _lock.lock()) + { + _jarConnection = null; + super.close(); + } } @Override - protected synchronized boolean checkConnection() + protected boolean checkConnection() { - super.checkConnection(); - try + try (AutoLock ignored = _lock.lock()) { - if (_jarConnection != _connection) - newConnection(); - } - catch (IOException e) - { - LOG.trace("IGNORED", e); - _jarConnection = null; - } + super.checkConnection(); + try + { + if (_jarConnection != _connection) + newConnection(); + } + catch (IOException e) + { + LOG.trace("IGNORED", e); + _jarConnection = null; + } - return _jarConnection != null; + return _jarConnection != null; + } } /** diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/URLResource.java b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/URLResource.java index 7561dd88b057..203ab064b8a9 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/URLResource.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/URLResource.java @@ -29,6 +29,7 @@ import java.nio.channels.ReadableByteChannel; import org.eclipse.jetty.util.URIUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,9 +39,10 @@ public class URLResource extends Resource { private static final Logger LOG = LoggerFactory.getLogger(URLResource.class); + + protected final AutoLock _lock = new AutoLock(); protected final URL _url; protected final String _urlString; - protected URLConnection _connection; protected InputStream _in = null; transient boolean _useCaches = Resource.__defaultUseCaches; @@ -58,44 +60,50 @@ protected URLResource(URL url, URLConnection connection, boolean useCaches) _useCaches = useCaches; } - protected synchronized boolean checkConnection() + protected boolean checkConnection() { - if (_connection == null) + try (AutoLock ignored = _lock.lock()) { - try + if (_connection == null) { - _connection = _url.openConnection(); - _connection.setUseCaches(_useCaches); - } - catch (IOException e) - { - LOG.trace("IGNORED", e); + try + { + _connection = _url.openConnection(); + _connection.setUseCaches(_useCaches); + } + catch (IOException e) + { + LOG.trace("IGNORED", e); + } } + return _connection != null; } - return _connection != null; } /** * Release any resources held by the resource. */ @Override - public synchronized void close() + public void close() { - if (_in != null) + try (AutoLock ignored = _lock.lock()) { - try - { - _in.close(); - } - catch (IOException e) + if (_in != null) { - LOG.trace("IGNORED", e); + try + { + _in.close(); + } + catch (IOException e) + { + LOG.trace("IGNORED", e); + } + _in = null; } - _in = null; - } - if (_connection != null) - _connection = null; + if (_connection != null) + _connection = null; + } } /** @@ -106,7 +114,7 @@ public boolean exists() { try { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (checkConnection() && _in == null) _in = _connection.getInputStream(); @@ -193,8 +201,7 @@ public String getName() * url connection will be nulled out to prevent re-use. */ @Override - public synchronized InputStream getInputStream() - throws java.io.IOException + public InputStream getInputStream() throws IOException { return getInputStream(true); //backwards compatibility } @@ -210,29 +217,31 @@ public synchronized InputStream getInputStream() * @return the inputstream for this resource * @throws IOException if unable to open the input stream */ - protected synchronized InputStream getInputStream(boolean resetConnection) - throws IOException + protected InputStream getInputStream(boolean resetConnection) throws IOException { - if (!checkConnection()) - throw new IOException("Invalid resource"); - - try + try (AutoLock ignored = _lock.lock()) { - if (_in != null) + if (!checkConnection()) + throw new IOException("Invalid resource"); + + try { - InputStream in = _in; - _in = null; - return in; + if (_in != null) + { + InputStream in = _in; + _in = null; + return in; + } + return _connection.getInputStream(); } - return _connection.getInputStream(); - } - finally - { - if (resetConnection) + finally { - _connection = null; - if (LOG.isDebugEnabled()) - LOG.debug("Connection nulled"); + if (resetConnection) + { + _connection = null; + if (LOG.isDebugEnabled()) + LOG.debug("Connection nulled"); + } } } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/security/Credential.java b/jetty-util/src/main/java/org/eclipse/jetty/util/security/Credential.java index 46aad34040e1..03bac4d9d133 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/security/Credential.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/security/Credential.java @@ -185,8 +185,6 @@ public static class MD5 extends Credential { private static final long serialVersionUID = 5533846540822684240L; private static final String __TYPE = "MD5:"; - private static final Object __md5Lock = new Object(); - private static MessageDigest __md; private final byte[] _digest; @@ -210,15 +208,8 @@ public boolean check(Object credentials) credentials = new String((char[])credentials); if (credentials instanceof Password || credentials instanceof String) { - byte[] digest; - synchronized (__md5Lock) - { - if (__md == null) - __md = MessageDigest.getInstance("MD5"); - __md.reset(); - __md.update(credentials.toString().getBytes(StandardCharsets.ISO_8859_1)); - digest = __md.digest(); - } + MessageDigest md5 = MessageDigest.getInstance("MD5"); + byte[] digest = md5.digest(credentials.toString().getBytes(StandardCharsets.ISO_8859_1)); return byteEquals(_digest, digest); } else if (credentials instanceof MD5) @@ -256,27 +247,8 @@ public static String digest(String password) { try { - byte[] digest; - synchronized (__md5Lock) - { - if (__md == null) - { - try - { - __md = MessageDigest.getInstance("MD5"); - } - catch (Exception e) - { - LOG.warn("Unable to access MD5 message digest", e); - return null; - } - } - - __md.reset(); - __md.update(password.getBytes(StandardCharsets.ISO_8859_1)); - digest = __md.digest(); - } - + MessageDigest md5 = MessageDigest.getInstance("MD5"); + byte[] digest = md5.digest(password.getBytes(StandardCharsets.ISO_8859_1)); return __TYPE + TypeUtil.toString(digest, 16); } catch (Exception e) diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/ssl/SslContextFactory.java b/jetty-util/src/main/java/org/eclipse/jetty/util/ssl/SslContextFactory.java index 8f1efd1af527..45e54a865a5c 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/ssl/SslContextFactory.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/ssl/SslContextFactory.java @@ -90,6 +90,7 @@ import org.eclipse.jetty.util.security.CertificateUtils; import org.eclipse.jetty.util.security.CertificateValidator; import org.eclipse.jetty.util.security.Password; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -137,6 +138,7 @@ public abstract class SslContextFactory extends AbstractLifeCycle implements Dum "^.*_anon_.*$" }; + private final AutoLock _lock = new AutoLock(); private final Set _excludeProtocols = new LinkedHashSet<>(); private final Set _includeProtocols = new LinkedHashSet<>(); private final Set _excludeCipherSuites = new LinkedHashSet<>(); @@ -212,7 +214,7 @@ public SslContextFactory(boolean trustAll) protected void doStart() throws Exception { super.doStart(); - synchronized (this) + try (AutoLock ignored = _lock.lock()) { load(); } @@ -436,7 +438,7 @@ List selectionDump() throws NoSuchAlgorithmException @Override protected void doStop() throws Exception { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { unload(); } @@ -1039,11 +1041,10 @@ public SSLContext getSslContext() if (!isStarted()) return _setContext; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_factory == null) throw new IllegalStateException("SslContextFactory reload failed"); - return _factory._context; } } @@ -1421,11 +1422,10 @@ public KeyStore getKeyStore() if (!isStarted()) return _setKeyStore; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_factory == null) throw new IllegalStateException("SslContextFactory reload failed"); - return _factory._keyStore; } } @@ -1445,11 +1445,10 @@ public KeyStore getTrustStore() if (!isStarted()) return _setTrustStore; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_factory == null) throw new IllegalStateException("SslContextFactory reload failed"); - return _factory._trustStore; } } @@ -1883,7 +1882,7 @@ public SSLParameters customize(SSLParameters sslParams) public void reload(Consumer consumer) throws Exception { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { consumer.accept(this); unload(); diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/statistic/RateStatistic.java b/jetty-util/src/main/java/org/eclipse/jetty/util/statistic/RateStatistic.java index 9743467c82b0..784be2055287 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/statistic/RateStatistic.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/statistic/RateStatistic.java @@ -23,6 +23,8 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import org.eclipse.jetty.util.thread.AutoLock; + /** *

Statistics on a time sequence rate.

*

Calculates the rate at which the {@link #record()} method is called @@ -34,6 +36,7 @@ */ public class RateStatistic { + private final AutoLock _lock = new AutoLock(); private final Deque _samples = new ArrayDeque<>(); private final long _nanoPeriod; private final TimeUnit _units; @@ -61,7 +64,7 @@ public TimeUnit getUnits() */ public void reset() { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _samples.clear(); _max = 0; @@ -88,7 +91,7 @@ private void update(long now) protected void age(long period, TimeUnit units) { long increment = TimeUnit.NANOSECONDS.convert(period, units); - synchronized (this) + try (AutoLock ignored = _lock.lock()) { int size = _samples.size(); for (int i = 0; i < size; i++) @@ -107,7 +110,7 @@ protected void age(long period, TimeUnit units) public int record() { long now = System.nanoTime(); - synchronized (this) + try (AutoLock ignored = _lock.lock()) { _count++; _samples.add(now); @@ -124,7 +127,7 @@ public int record() */ public int getRate() { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { update(); return _samples.size(); @@ -136,10 +139,7 @@ public int getRate() */ public long getMax() { - synchronized (this) - { - return _max; - } + return _lock.runLocked(() -> _max); } /** @@ -148,7 +148,7 @@ public long getMax() */ public long getOldest(TimeUnit units) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { Long head = _samples.peekFirst(); if (head == null) @@ -162,10 +162,7 @@ public long getOldest(TimeUnit units) */ public long getCount() { - synchronized (this) - { - return _count; - } + return _lock.runLocked(() -> _count); } public String dump() @@ -176,7 +173,7 @@ public String dump() public String dump(TimeUnit units) { long now = System.nanoTime(); - synchronized (this) + try (AutoLock ignored = _lock.lock()) { String samples = _samples.stream() .mapToLong(t -> units.convert(now - t, TimeUnit.NANOSECONDS)) @@ -194,7 +191,7 @@ public String toString() private String toString(long nanoTime) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { update(nanoTime); return String.format("%s@%x{count=%d,max=%d,rate=%d per %d %s}", diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/AutoLock.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/AutoLock.java index 34f9aebdaf98..bac7edbf626e 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/AutoLock.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/AutoLock.java @@ -18,11 +18,15 @@ package org.eclipse.jetty.util.thread; +import java.io.Serializable; +import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; /** - * Reentrant lock that can be used in a try-with-resources statement. + *

Reentrant lock that can be used in a try-with-resources statement.

+ *

Typical usage:

*
  * try (AutoLock lock = this.lock.lock())
  * {
@@ -30,7 +34,7 @@
  * }
  * 
*/ -public class AutoLock implements AutoCloseable +public class AutoLock implements AutoCloseable, Serializable { private final ReentrantLock _lock = new ReentrantLock(); @@ -45,6 +49,57 @@ public AutoLock lock() return this; } + /** + *

Runs the given code with the lock held.

+ *

This is equivalent to:

+ *
+     * try (AutoLock ignored = lock())
+     * {
+     *     code.run();
+     * }
+     * 
+ * + * @param code the code to run with the lock held. + */ + public void runLocked(Runnable code) + { + try (AutoLock ignored = lock()) + { + code.run(); + } + } + + /** + *

Returns the result of running the given code with the lock held.

+ *

This is equivalent to:

+ *
+     * try (AutoLock ignored = lock())
+     * {
+     *     return code.get();
+     * }
+     * 
+ * + * @param code the code to run with the lock held. + * @param the result type + * @return the result of the code run + */ + public T runLocked(Supplier code) + { + try (AutoLock ignored = lock()) + { + return code.get(); + } + } + + /** + * @see ReentrantLock#isHeldByCurrentThread() + * @return whether this lock is held by the current thread + */ + public boolean isHeldByCurrentThread() + { + return _lock.isHeldByCurrentThread(); + } + /** * @return a {@link Condition} associated with this lock */ @@ -64,4 +119,69 @@ public void close() { _lock.unlock(); } + + /** + *

A reentrant lock with a condition that can be used in a try-with-resources statement.

+ *

Typical usage:

+ *
+     * // Waiting
+     * try (AutoLock lock = _lock.lock())
+     * {
+     *     lock.await();
+     * }
+     *
+     * // Signaling
+     * try (AutoLock lock = _lock.lock())
+     * {
+     *     lock.signalAll();
+     * }
+     * 
+ */ + public static class WithCondition extends AutoLock + { + private final Condition _condition = newCondition(); + + @Override + public AutoLock.WithCondition lock() + { + return (WithCondition)super.lock(); + } + + /** + * @see Condition#signal() + */ + public void signal() + { + _condition.signal(); + } + + /** + * @see Condition#signalAll() + */ + public void signalAll() + { + _condition.signalAll(); + } + + /** + * @see Condition#await() + * @throws InterruptedException if the current thread is interrupted + */ + public void await() throws InterruptedException + { + _condition.await(); + } + + /** + * @see Condition#await(long, TimeUnit) + * @param time the time to wait + * @param unit the time unit + * @return false if the waiting time elapsed + * @throws InterruptedException if the current thread is interrupted + */ + public boolean await(long time, TimeUnit unit) throws InterruptedException + { + return _condition.await(time, unit); + } + } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java index c4fab5abbfaa..6accd65fe3b8 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java @@ -64,7 +64,7 @@ public class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor private final AtomicBiInteger _counts = new AtomicBiInteger(Integer.MIN_VALUE, 0); private final AtomicLong _lastShrink = new AtomicLong(); private final Set _threads = ConcurrentHashMap.newKeySet(); - private final Object _joinLock = new Object(); + private final AutoLock.WithCondition _joinLock = new AutoLock.WithCondition(); private final BlockingQueue _jobs; private final ThreadGroup _threadGroup; private final ThreadFactory _threadFactory; @@ -277,9 +277,9 @@ else if (job != NOOP) if (_budget != null) _budget.reset(); - synchronized (_joinLock) + try (AutoLock.WithCondition lock = _joinLock.lock()) { - _joinLock.notifyAll(); + lock.signalAll(); } } @@ -570,11 +570,11 @@ public boolean tryExecute(Runnable task) @Override public void join() throws InterruptedException { - synchronized (_joinLock) + try (AutoLock.WithCondition lock = _joinLock.lock()) { while (isRunning()) { - _joinLock.wait(); + lock.await(); } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java index c38fa02a63bd..be74c189ba33 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java @@ -18,6 +18,7 @@ package org.eclipse.jetty.util.thread; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -36,10 +37,11 @@ public class ShutdownThread extends Thread { private static final Logger LOG = LoggerFactory.getLogger(ShutdownThread.class); - private static final ShutdownThread _thread = new ShutdownThread(); + private static final ShutdownThread INSTANCE = new ShutdownThread(); + private final AutoLock _lock = new AutoLock(); + private final List _lifeCycles = new CopyOnWriteArrayList<>(); private boolean _hooked; - private final List _lifeCycles = new CopyOnWriteArrayList(); /** * Default constructor for the singleton @@ -51,9 +53,9 @@ private ShutdownThread() super("JettyShutdownThread"); } - private synchronized void hook() + private void hook() { - try + try (AutoLock ignored = _lock.lock()) { if (!_hooked) Runtime.getRuntime().addShutdownHook(this); @@ -66,9 +68,9 @@ private synchronized void hook() } } - private synchronized void unhook() + private void unhook() { - try + try (AutoLock ignored = _lock.lock()) { _hooked = false; Runtime.getRuntime().removeShutdownHook(this); @@ -81,45 +83,53 @@ private synchronized void unhook() } /** - * Returns the instance of the singleton - * - * @return the singleton instance of the {@link ShutdownThread} + * @return the singleton instance of the ShutdownThread */ public static ShutdownThread getInstance() { - return _thread; + return INSTANCE; } - public static synchronized void register(LifeCycle... lifeCycles) + public static void register(LifeCycle... lifeCycles) { - _thread._lifeCycles.addAll(Arrays.asList(lifeCycles)); - if (_thread._lifeCycles.size() > 0) - _thread.hook(); + try (AutoLock ignored = INSTANCE._lock.lock()) + { + INSTANCE._lifeCycles.addAll(Arrays.asList(lifeCycles)); + if (INSTANCE._lifeCycles.size() > 0) + INSTANCE.hook(); + } } - public static synchronized void register(int index, LifeCycle... lifeCycles) + public static void register(int index, LifeCycle... lifeCycles) { - _thread._lifeCycles.addAll(index, Arrays.asList(lifeCycles)); - if (_thread._lifeCycles.size() > 0) - _thread.hook(); + try (AutoLock ignored = INSTANCE._lock.lock()) + { + INSTANCE._lifeCycles.addAll(index, Arrays.asList(lifeCycles)); + if (INSTANCE._lifeCycles.size() > 0) + INSTANCE.hook(); + } } - public static synchronized void deregister(LifeCycle lifeCycle) + public static void deregister(LifeCycle lifeCycle) { - _thread._lifeCycles.remove(lifeCycle); - if (_thread._lifeCycles.size() == 0) - _thread.unhook(); + try (AutoLock ignored = INSTANCE._lock.lock()) + { + INSTANCE._lifeCycles.remove(lifeCycle); + if (INSTANCE._lifeCycles.size() == 0) + INSTANCE.unhook(); + } } - public static synchronized boolean isRegistered(LifeCycle lifeCycle) + public static boolean isRegistered(LifeCycle lifeCycle) { - return _thread._lifeCycles.contains(lifeCycle); + return INSTANCE._lock.runLocked(() -> INSTANCE._lifeCycles.contains(lifeCycle)); } @Override public void run() { - for (LifeCycle lifeCycle : _thread._lifeCycles) + List lifeCycles = INSTANCE._lock.runLocked(() -> new ArrayList<>(INSTANCE._lifeCycles)); + for (LifeCycle lifeCycle : lifeCycles) { try { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/strategy/EatWhatYouKill.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/strategy/EatWhatYouKill.java index b295092fc066..5b2cb557246c 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/strategy/EatWhatYouKill.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/strategy/EatWhatYouKill.java @@ -29,6 +29,7 @@ import org.eclipse.jetty.util.annotation.ManagedObject; import org.eclipse.jetty.util.annotation.ManagedOperation; import org.eclipse.jetty.util.component.ContainerLifeCycle; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.ExecutionStrategy; import org.eclipse.jetty.util.thread.Invocable; import org.eclipse.jetty.util.thread.TryExecutor; @@ -72,6 +73,7 @@ private enum Mode EXECUTE_PRODUCE_CONSUME // Eat What You Kill! } + private final AutoLock _lock = new AutoLock(); private final LongAdder _pcMode = new LongAdder(); private final LongAdder _picMode = new LongAdder(); private final LongAdder _pecMode = new LongAdder(); @@ -97,7 +99,7 @@ public EatWhatYouKill(Producer producer, Executor executor) public void dispatch() { boolean execute = false; - synchronized (this) + try (AutoLock ignored = _lock.lock()) { switch (_state) { @@ -140,7 +142,7 @@ private void tryProduce(boolean wasPending) if (LOG.isDebugEnabled()) LOG.debug("{} tryProduce {}", this, wasPending); - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (wasPending) _pending = false; @@ -185,7 +187,7 @@ private boolean doProduce(boolean nonBlocking) if (task == null) { - synchronized (this) + try (AutoLock ignored = _lock.lock()) { // Could another task just have been queued with a produce call? switch (_state) @@ -237,7 +239,7 @@ private boolean doProduce(boolean nonBlocking) case BLOCKING: // The task is blocking, so PC is not an option. Thus we choose // between EPC and PEC based on the availability of a reserved thread. - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_pending) { @@ -260,7 +262,7 @@ else if (_tryExecutor.tryExecute(this)) case EITHER: // The task may be non blocking, so PC is an option. Thus we choose // between EPC and PC based on the availability of a reserved thread. - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_pending) { @@ -313,7 +315,7 @@ else if (_tryExecutor.tryExecute(this)) runTask(task); // Try to produce again? - synchronized (this) + try (AutoLock ignored = _lock.lock()) { if (_state == State.IDLE) { @@ -420,10 +422,7 @@ public long getEPCTasksConsumed() @ManagedAttribute(value = "whether this execution strategy is idle", readonly = true) public boolean isIdle() { - synchronized (this) - { - return _state == State.IDLE; - } + return _lock.runLocked(() -> _state == State.IDLE); } @ManagedOperation(value = "resets the task counts", impact = "ACTION") @@ -438,10 +437,7 @@ public void reset() @Override public String toString() { - synchronized (this) - { - return toStringLocked(); - } + return _lock.runLocked(this::toStringLocked); } public String toStringLocked() diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java index c43eac366bd0..aaf98302a394 100644 --- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java +++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java @@ -41,6 +41,7 @@ import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.component.DumpableCollection; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,15 +67,18 @@ public class Configurations extends AbstractList implements Dumpable { private static final Logger LOG = LoggerFactory.getLogger(Configurations.class); - + private static final AutoLock __lock = new AutoLock(); private static final List __known = new ArrayList<>(); private static final List __unavailable = new ArrayList<>(); private static final Set __knownByClassName = new HashSet<>(); - public static synchronized List getKnown() + public static List getKnown() { - if (__known.isEmpty()) + try (AutoLock ignored = __lock.lock()) { + if (!__known.isEmpty()) + return __known; + TypeUtil.serviceProviderStream(ServiceLoader.load(Configuration.class)).forEach(provider -> { try @@ -95,7 +99,6 @@ public static synchronized List getKnown() LOG.warn("Unable to get known Configuration", e); } }); - sort(__known); if (LOG.isDebugEnabled()) { @@ -105,53 +108,62 @@ public static synchronized List getKnown() } } - LOG.debug("Known Configurations {}", __knownByClassName); + if (LOG.isDebugEnabled()) + LOG.debug("Known Configurations {}", __knownByClassName); + return __known; } - return __known; } - public static synchronized void setKnown(String... classes) + public static void setKnown(String... classes) { - if (!__known.isEmpty()) - throw new IllegalStateException("Known configuration classes already set"); - - for (String c : classes) + try (AutoLock ignored = __lock.lock()) { - try + if (!__known.isEmpty()) + throw new IllegalStateException("Known configuration classes already set"); + + for (String c : classes) { - Class clazz = Loader.loadClass(c); - Configuration configuration = clazz.getConstructor().newInstance(); - if (!configuration.isAvailable()) + try { - if (LOG.isDebugEnabled()) - LOG.warn("Configuration unavailable: " + configuration); - __unavailable.add(configuration); - continue; + Class clazz = Loader.loadClass(c); + Configuration configuration = clazz.getConstructor().newInstance(); + if (!configuration.isAvailable()) + { + if (LOG.isDebugEnabled()) + LOG.warn("Configuration unavailable: " + configuration); + __unavailable.add(configuration); + continue; + } + __known.add(clazz.getConstructor().newInstance()); + __knownByClassName.add(c); + } + catch (Exception e) + { + LOG.warn("Problem loading known class", e); } - __known.add(clazz.getConstructor().newInstance()); - __knownByClassName.add(c); - } - catch (Exception e) - { - LOG.warn("Problem loading known class", e); } - } - sort(__known); - if (LOG.isDebugEnabled()) - { - for (Configuration c : __known) + sort(__known); + if (LOG.isDebugEnabled()) { - LOG.debug("known {}", c); + for (Configuration c : __known) + { + LOG.debug("known {}", c); + } } - } - LOG.debug("Known Configurations {}", __knownByClassName); + if (LOG.isDebugEnabled()) + LOG.debug("Known Configurations {}", __knownByClassName); + } } - static synchronized void cleanKnown() + // Only used by tests. + static void clearKnown() { - __known.clear(); - __unavailable.clear(); + try (AutoLock ignored = __lock.lock()) + { + __known.clear(); + __unavailable.clear(); + } } /** diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java index 5afc94ae9b9d..b778e6657184 100644 --- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java +++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java @@ -29,6 +29,7 @@ import org.eclipse.jetty.util.resource.EmptyResource; import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,6 +46,7 @@ public class MetaData public static final String ORDERED_LIBS = "javax.servlet.context.orderedLibs"; public static final Resource NON_FRAG_RESOURCE = EmptyResource.INSTANCE; + private final AutoLock _lock = new AutoLock(); protected Map _origins = new HashMap<>(); protected WebDescriptor _webDefaultsRoot; protected WebDescriptor _webXmlRoot; @@ -360,41 +362,38 @@ public void addDiscoveredAnnotations(List annotations) * * @param annotation the discovered annotation */ - public synchronized void addDiscoveredAnnotation(DiscoveredAnnotation annotation) + public void addDiscoveredAnnotation(DiscoveredAnnotation annotation) { if (annotation == null) return; - //if no resource associated with an annotation map it to empty resource - these - //annotations will always be processed first - Resource enclosingResource = EmptyResource.INSTANCE; - Resource resource = annotation.getResource(); - if (resource != null) + try (AutoLock ignored = _lock.lock()) { - //check if any of the web-inf classes dirs is a parent - enclosingResource = getEnclosingResource(_webInfClasses, resource); + //if no resource associated with an annotation map it to empty resource - these + //annotations will always be processed first + Resource enclosingResource = EmptyResource.INSTANCE; + Resource resource = annotation.getResource(); + if (resource != null) + { + //check if any of the web-inf classes dirs is a parent + enclosingResource = getEnclosingResource(_webInfClasses, resource); - //check if any of the web-inf jars is a parent - if (enclosingResource == null) - enclosingResource = getEnclosingResource(_webInfJars, resource); + //check if any of the web-inf jars is a parent + if (enclosingResource == null) + enclosingResource = getEnclosingResource(_webInfJars, resource); - //check if any of the container resources is a parent - if (enclosingResource == null) - enclosingResource = getEnclosingResource(_orderedContainerResources, resource); + //check if any of the container resources is a parent + if (enclosingResource == null) + enclosingResource = getEnclosingResource(_orderedContainerResources, resource); - //Couldn't find a parent resource in any of the known resources, map it to the empty resource - if (enclosingResource == null) - enclosingResource = EmptyResource.INSTANCE; - } + //Couldn't find a parent resource in any of the known resources, map it to the empty resource + if (enclosingResource == null) + enclosingResource = EmptyResource.INSTANCE; + } - List list = _annotations.get(enclosingResource); - if (list == null) - { - list = new ArrayList<>(); - _annotations.put(enclosingResource, list); + List list = _annotations.computeIfAbsent(enclosingResource, k -> new ArrayList<>()); + list.add(annotation); } - - list.add(annotation); } /** diff --git a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/ConfigurationsTest.java b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/ConfigurationsTest.java index 02c8632211e3..c0c4622969b8 100644 --- a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/ConfigurationsTest.java +++ b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/ConfigurationsTest.java @@ -34,13 +34,13 @@ public class ConfigurationsTest @AfterEach public void tearDown() { - Configurations.cleanKnown(); + Configurations.clearKnown(); } @BeforeEach public void setup() { - Configurations.cleanKnown(); + Configurations.clearKnown(); } @Test diff --git a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java index 17c9fc6336cc..481923fa079f 100644 --- a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java +++ b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java @@ -76,7 +76,7 @@ public void sessionDestroyed(HttpSessionEvent se) @AfterEach public void tearDown() { - Configurations.cleanKnown(); + Configurations.clearKnown(); } @Test @@ -157,7 +157,7 @@ public void testSessionListeners() @Test public void testConfigurationClassesFromDefault() { - Configurations.cleanKnown(); + Configurations.clearKnown(); String[] knownAndEnabled = Configurations.getKnown().stream() .filter(c -> c.isEnabledByDefault()) .map(c -> c.getClass().getName()) @@ -182,7 +182,7 @@ public void testConfigurationClassesFromDefault() @Test public void testConfigurationOrder() { - Configurations.cleanKnown(); + Configurations.clearKnown(); WebAppContext wac = new WebAppContext(); wac.setServer(new Server()); assertThat(wac.getConfigurations().stream().map(c -> c.getClass().getName()).collect(Collectors.toList()), @@ -199,7 +199,7 @@ public void testConfigurationOrder() @Test public void testConfigurationInstances() { - Configurations.cleanKnown(); + Configurations.clearKnown(); Configuration[] configs = {new WebInfConfiguration()}; WebAppContext wac = new WebAppContext(); wac.setConfigurations(configs); diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameFlusher.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameFlusher.java index e4483f6e7194..f763c961cd29 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameFlusher.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameFlusher.java @@ -35,6 +35,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.IteratingCallback; import org.eclipse.jetty.util.TypeUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Scheduler; import org.eclipse.jetty.websocket.core.CloseStatus; import org.eclipse.jetty.websocket.core.Frame; @@ -50,6 +51,7 @@ public class FrameFlusher extends IteratingCallback private static final Logger LOG = LoggerFactory.getLogger(FrameFlusher.class); private static final Throwable CLOSED_CHANNEL = new ClosedChannelException(); + private final AutoLock lock = new AutoLock(); private final LongAdder messagesOut = new LongAdder(); private final LongAdder bytesOut = new LongAdder(); private final ByteBufferPool bufferPool; @@ -114,7 +116,7 @@ public boolean enqueue(Frame frame, Callback callback, boolean batch) List failedEntries = null; CloseStatus closeStatus = null; - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (canEnqueue) { @@ -186,11 +188,7 @@ public boolean enqueue(Frame frame, Callback callback, boolean batch) public void onClose(Throwable cause) { - synchronized (this) - { - closedCause = cause == null ? CLOSED_CHANNEL : cause; - } - + lock.runLocked(() -> closedCause = cause == null ? CLOSED_CHANNEL : cause); iterate(); } @@ -202,7 +200,7 @@ protected Action process() throws Throwable boolean flush = false; Callback releasingCallback = this; - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (closedCause != null) throw closedCause; @@ -349,16 +347,13 @@ private ByteBuffer acquireBuffer(int capacity) private int getQueueSize() { - synchronized (this) - { - return queue.size(); - } + return lock.runLocked(queue::size); } public void timeoutExpired() { boolean failed = false; - synchronized (FrameFlusher.this) + try (AutoLock ignored = lock.lock()) { if (closedCause != null) return; @@ -409,7 +404,7 @@ public void onCompleteFailure(Throwable failure) { BufferUtil.clear(batchBuffer); releaseAggregate(); - synchronized (this) + try (AutoLock ignored = lock.lock()) { failedEntries.addAll(queue); queue.clear(); diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameSequence.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameSequence.java index 5bc9d1282700..c2d1ba278e8e 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameSequence.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameSequence.java @@ -18,17 +18,19 @@ package org.eclipse.jetty.websocket.core.internal; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.websocket.core.OpCode; import org.eclipse.jetty.websocket.core.exception.ProtocolException; public class FrameSequence { + private final AutoLock lock = new AutoLock(); // TODO should we be able to get a non fin frame then get a close frame without error private byte state = OpCode.UNDEFINED; public void check(byte opcode, boolean fin) throws ProtocolException { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (state == OpCode.CLOSE) throw new ProtocolException(OpCode.name(opcode) + " after CLOSE"); diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/TransformingFlusher.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/TransformingFlusher.java index 28d30165aa38..b73166ab2ce0 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/TransformingFlusher.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/TransformingFlusher.java @@ -23,6 +23,7 @@ import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.IteratingCallback; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.websocket.core.Frame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,6 +39,7 @@ public abstract class TransformingFlusher { private final Logger log = LoggerFactory.getLogger(this.getClass()); + private final AutoLock lock = new AutoLock(); private final Queue entries = new ArrayDeque<>(); private final IteratingCallback flusher = new Flusher(); private boolean finished = true; @@ -68,12 +70,10 @@ public final void sendFrame(Frame frame, Callback callback, boolean batch) log.debug("Queuing {}", entry); boolean enqueued = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (failure == null) - { enqueued = entries.add(entry); - } } if (enqueued) @@ -84,7 +84,7 @@ public final void sendFrame(Frame frame, Callback callback, boolean batch) private void onFailure(Throwable t) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (failure == null) failure = t; @@ -97,10 +97,7 @@ private void onFailure(Throwable t) private FrameEntry pollEntry() { - synchronized (this) - { - return entries.poll(); - } + return lock.runLocked(entries::poll); } private class Flusher extends IteratingCallback implements Callback @@ -137,7 +134,7 @@ protected Action process() protected void onCompleteFailure(Throwable t) { if (log.isDebugEnabled()) - log.debug("failed {}", t); + log.debug("failed to flush", t); notifyCallbackFailure(current.callback, t); current = null; diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketConnection.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketConnection.java index 74497c7a235d..d13f6626b317 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketConnection.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketConnection.java @@ -35,6 +35,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.component.Dumpable; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.util.thread.Scheduler; import org.eclipse.jetty.websocket.core.Behavior; import org.eclipse.jetty.websocket.core.Frame; @@ -54,19 +55,17 @@ public class WebSocketConnection extends AbstractConnection implements Connectio */ private static final int MIN_BUFFER_SIZE = Generator.MAX_HEADER_LENGTH; + private final AutoLock lock = new AutoLock(); private final ByteBufferPool bufferPool; private final Generator generator; private final Parser parser; private final WebSocketCoreSession coreSession; - private final Flusher flusher; private final Random random; - private long demand; private boolean fillingAndParsing; private final LongAdder messagesIn = new LongAdder(); private final LongAdder bytesIn = new LongAdder(); - // Read / Parse variables private RetainableByteBuffer networkBuffer; private boolean useInputDirectByteBuffers; @@ -265,7 +264,7 @@ public void failed(Throwable cause) private void acquireNetworkBuffer() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (networkBuffer == null) networkBuffer = newNetworkBuffer(getInputBufferSize()); @@ -274,7 +273,7 @@ private void acquireNetworkBuffer() private void reacquireNetworkBuffer() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (networkBuffer == null) throw new IllegalStateException(); @@ -294,7 +293,7 @@ private RetainableByteBuffer newNetworkBuffer(int capacity) private void releaseNetworkBuffer() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (networkBuffer == null) throw new IllegalStateException(); @@ -329,7 +328,7 @@ public void demand(long n) throw new IllegalArgumentException("Demand must be positive"); boolean fillAndParse = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("demand {} d={} fp={} {} {}", n, demand, fillingAndParsing, networkBuffer, this); @@ -362,7 +361,7 @@ public void demand(long n) public boolean moreDemand() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("moreDemand? d={} fp={} {} {}", demand, fillingAndParsing, networkBuffer, this); @@ -382,7 +381,7 @@ public boolean moreDemand() public boolean meetDemand() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("meetDemand d={} fp={} {} {}", demand, fillingAndParsing, networkBuffer, this); @@ -401,11 +400,10 @@ public boolean meetDemand() public void cancelDemand() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("cancelDemand d={} fp={} {} {}", demand, fillingAndParsing, networkBuffer, this); - demand = -1; } } @@ -489,10 +487,7 @@ protected void setInitialBuffer(ByteBuffer initialBuffer) { if (LOG.isDebugEnabled()) LOG.debug("Set initial buffer - {}", BufferUtil.toDetailString(initialBuffer)); - synchronized (this) - { - networkBuffer = newNetworkBuffer(initialBuffer.remaining()); - } + lock.runLocked(() -> networkBuffer = newNetworkBuffer(initialBuffer.remaining())); ByteBuffer buffer = networkBuffer.getBuffer(); BufferUtil.clearToFill(buffer); BufferUtil.put(initialBuffer, buffer); diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketSessionState.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketSessionState.java index 6054ab8068f3..a2926af60fee 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketSessionState.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketSessionState.java @@ -21,6 +21,7 @@ import java.nio.channels.ClosedChannelException; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.websocket.core.CloseStatus; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; @@ -41,6 +42,7 @@ enum State CLOSED } + private final AutoLock lock = new AutoLock(); private State _sessionState = State.CONNECTING; private byte _incomingContinuation = OpCode.UNDEFINED; private byte _outgoingContinuation = OpCode.UNDEFINED; @@ -48,7 +50,7 @@ enum State public void onConnected() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (_sessionState != State.CONNECTING) throw new IllegalStateException(_sessionState.toString()); @@ -59,7 +61,7 @@ public void onConnected() public void onOpen() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { switch (_sessionState) { @@ -78,12 +80,9 @@ public void onOpen() } } - public State getState() + private State getState() { - synchronized (this) - { - return _sessionState; - } + return lock.runLocked(() -> _sessionState); } public boolean isClosed() @@ -105,15 +104,12 @@ public boolean isOutputOpen() public CloseStatus getCloseStatus() { - synchronized (this) - { - return _closeStatus; - } + return lock.runLocked(() -> _closeStatus); } public boolean onClosed(CloseStatus closeStatus) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (_sessionState == State.CLOSED) return false; @@ -142,7 +138,7 @@ public boolean onClosed(CloseStatus closeStatus) */ public void onError(Throwable t) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (_sessionState != State.CLOSED || _closeStatus == null) throw new IllegalArgumentException(); @@ -159,7 +155,7 @@ public void onError(Throwable t) public boolean onEof() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { switch (_sessionState) { @@ -181,7 +177,7 @@ public boolean onOutgoingFrame(Frame frame) throws Exception byte opcode = frame.getOpCode(); boolean fin = frame.isFin(); - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (!isOutputOpen()) throw new ClosedChannelException(); @@ -224,7 +220,7 @@ public boolean onIncomingFrame(Frame frame) throws ProtocolException byte opcode = frame.getOpCode(); boolean fin = frame.isFin(); - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (!isInputOpen()) throw new IllegalStateException(_sessionState.toString()); diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java index 4fe629afd7c6..d1a9aa5c093d 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java @@ -37,6 +37,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.websocket.core.CloseStatus; import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; @@ -60,55 +61,25 @@ public class JavaxWebSocketFrameHandler implements FrameHandler { + private final AutoLock lock = new AutoLock(); + private final AtomicBoolean closeNotified = new AtomicBoolean(); + private final Map messageHandlerMap = new HashMap<>(); private final Logger logger; private final JavaxWebSocketContainer container; private final Object endpointInstance; - private final AtomicBoolean closeNotified = new AtomicBoolean(); - - /** - * List of configured named variables in the uri-template. - *

- * Used to bind uri-template variables, with their values from the upgrade, to the methods - * that have declared their interest in these values via {@code @PathParam} annotations. - *

- *

- * Can be null if client side, or no named variables were configured on the server side. - *

- */ - /** - * The Map of path parameter values that arrived during the server side upgrade process. - *

- * Used to bind uri-template variables, with their values from the upgrade, to the methods - * that have declared their interest in these values via {@code @PathParam} annotations. - *

- *

- * The values are represented as {@link String} and are essentially static for this - * instance of the the JavaxWebSocketFrameHandler. They will be converted to the - * type declared by the {@code @PathParam} annotations following the JSR356 advice - * to only support String, Java Primitives (or their Boxed version). - *

- *

- * Can be null if client side, or no named variables were configured on the server side, - * or the server side component didn't use the {@link org.eclipse.jetty.http.pathmap.UriTemplatePathSpec} for its mapping. - *

- */ private MethodHandle openHandle; private MethodHandle closeHandle; private MethodHandle errorHandle; private MethodHandle pongHandle; private JavaxWebSocketMessageMetadata textMetadata; private JavaxWebSocketMessageMetadata binaryMetadata; - private UpgradeRequest upgradeRequest; - private EndpointConfig endpointConfig; - private final Map messageHandlerMap = new HashMap<>(); private MessageSink textSink; private MessageSink binarySink; private MessageSink activeMessageSink; private JavaxWebSocketSession session; private CoreSession coreSession; - protected byte dataType = OpCode.UNDEFINED; public JavaxWebSocketFrameHandler(JavaxWebSocketContainer container, @@ -526,7 +497,7 @@ private void registerMessageHandler(Class clazz, MessageHandler handler, byte private MessageSink registerMessageHandler(byte basicWebSocketMessageType, Class handlerType, MessageHandler handler, MessageSink messageSink) { - synchronized (messageHandlerMap) + try (AutoLock ignored = lock.lock()) { RegisteredMessageHandler registeredHandler = messageHandlerMap.get(basicWebSocketMessageType); if (registeredHandler != null) @@ -546,7 +517,7 @@ private MessageSink registerMessageHandler(byte basicWebSocketMessageType, C public void removeMessageHandler(MessageHandler handler) { - synchronized (messageHandlerMap) + try (AutoLock ignored = lock.lock()) { Optional> optionalEntry = messageHandlerMap.entrySet().stream() .filter((entry) -> entry.getValue().getMessageHandler().equals(handler)) diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketSession.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketSession.java index 526a7ff97bfd..13b4701fd2b3 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketSession.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketSession.java @@ -565,7 +565,7 @@ public boolean isSecure() } @Override - public synchronized void removeMessageHandler(MessageHandler handler) + public void removeMessageHandler(MessageHandler handler) { frameHandler.removeMessageHandler(handler); } diff --git a/jetty-websocket/websocket-jetty-client/src/main/java/org/eclipse/jetty/websocket/client/WebSocketClient.java b/jetty-websocket/websocket-jetty-client/src/main/java/org/eclipse/jetty/websocket/client/WebSocketClient.java index dc5588d37c23..da4760d655f7 100644 --- a/jetty-websocket/websocket-jetty-client/src/main/java/org/eclipse/jetty/websocket/client/WebSocketClient.java +++ b/jetty-websocket/websocket-jetty-client/src/main/java/org/eclipse/jetty/websocket/client/WebSocketClient.java @@ -375,7 +375,7 @@ public SslContextFactory getSslContextFactory() * @see Runtime#addShutdownHook(Thread) * @see ShutdownThread */ - public synchronized void setStopAtShutdown(boolean stop) + public void setStopAtShutdown(boolean stop) { if (stop) { diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java index c2b8c5bee96d..ae0d26754055 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java +++ b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java @@ -26,6 +26,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.websocket.api.BatchMode; import org.eclipse.jetty.websocket.api.UpgradeRequest; import org.eclipse.jetty.websocket.api.UpgradeResponse; @@ -60,6 +61,7 @@ private enum SuspendState CLOSED } + private final AutoLock lock = new AutoLock(); private final Logger log; private final WebSocketContainer container; private final Object endpointInstance; @@ -189,7 +191,7 @@ public void onOpen(CoreSession coreSession, Callback callback) @Override public void onFrame(Frame frame, Callback callback) { - synchronized (this) + try (AutoLock ignored = lock.lock()) { switch (state) { @@ -298,11 +300,8 @@ private void onCloseFrame(Frame frame, Callback callback) @Override public void onClosed(CloseStatus closeStatus, Callback callback) { - synchronized (this) - { - // We are now closed and cannot suspend or resume. - state = SuspendState.CLOSED; - } + // We are now closed and cannot suspend or resume. + lock.runLocked(() -> state = SuspendState.CLOSED); notifyOnClose(closeStatus, callback); container.notifySessionListeners((listener) -> listener.onWebSocketSessionClosed(session)); @@ -425,7 +424,7 @@ public boolean isDemanding() public void suspend() { - synchronized (this) + try (AutoLock ignored = lock.lock()) { switch (state) { @@ -443,7 +442,7 @@ public void resume() { boolean needDemand = false; Runnable delayedFrame = null; - synchronized (this) + try (AutoLock ignored = lock.lock()) { switch (state) { @@ -480,7 +479,7 @@ public void resume() private void demand() { boolean demand = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { switch (state) { diff --git a/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java index 54ed65b55bdc..f92295a0cef4 100644 --- a/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java @@ -29,6 +29,7 @@ import org.eclipse.jetty.util.BlockingArrayQueue; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.websocket.core.Frame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,6 +45,8 @@ public class MessageInputStream extends InputStream implements MessageSink private static final Logger LOG = LoggerFactory.getLogger(MessageInputStream.class); private static final Entry EOF = new Entry(BufferUtil.EMPTY_BUFFER, Callback.NOOP); private static final Entry CLOSED = new Entry(BufferUtil.EMPTY_BUFFER, Callback.NOOP); + + private final AutoLock lock = new AutoLock(); private final BlockingArrayQueue buffers = new BlockingArrayQueue<>(); private boolean closed = false; private Entry currentEntry; @@ -56,7 +59,7 @@ public void accept(Frame frame, Callback callback) LOG.debug("accepting {}", frame); boolean succeed = false; - synchronized (this) + try (AutoLock ignored = lock.lock()) { // If closed or we have no payload, request the next frame. if (closed || (!frame.hasPayload() && !frame.isFin())) @@ -134,7 +137,7 @@ public void close() throws IOException LOG.debug("close()"); ArrayList entries = new ArrayList<>(); - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (closed) return; @@ -169,7 +172,7 @@ public void setTimeout(long timeoutMs) private void succeedCurrentEntry() { Entry current; - synchronized (this) + try (AutoLock ignored = lock.lock()) { current = currentEntry; currentEntry = null; @@ -180,7 +183,7 @@ private void succeedCurrentEntry() private Entry getCurrentEntry() throws IOException { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (currentEntry != null) return currentEntry; @@ -205,7 +208,7 @@ private Entry getCurrentEntry() throws IOException throw new IOException(String.format("Read timeout: %,dms expired", timeoutMs)); } - synchronized (this) + try (AutoLock ignored = lock.lock()) { currentEntry = result; return currentEntry; diff --git a/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java index 389fd20eaf56..ab7087d4b464 100644 --- a/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java @@ -26,6 +26,7 @@ import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.FutureCallback; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.websocket.core.CoreSession; import org.eclipse.jetty.websocket.core.Frame; import org.eclipse.jetty.websocket.core.OpCode; @@ -39,6 +40,7 @@ public class MessageOutputStream extends OutputStream { private static final Logger LOG = LoggerFactory.getLogger(MessageOutputStream.class); + private final AutoLock lock = new AutoLock(); private final CoreSession coreSession; private final ByteBufferPool bufferPool; private final int bufferSize; @@ -123,7 +125,7 @@ public void flush() throws IOException private void flush(boolean fin) throws IOException { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (closed) throw new IOException("Stream is closed"); @@ -157,7 +159,7 @@ private void flush(boolean fin) throws IOException private void send(ByteBuffer data) throws IOException { - synchronized (this) + try (AutoLock ignored = lock.lock()) { if (closed) throw new IOException("Stream is closed"); @@ -197,35 +199,20 @@ public void close() throws IOException public void setCallback(Callback callback) { - synchronized (this) - { - this.callback = callback; - } + lock.runLocked(() -> this.callback = callback); } private void notifySuccess() { - Callback callback; - synchronized (this) - { - callback = this.callback; - } + Callback callback = lock.runLocked(() -> this.callback); if (callback != null) - { callback.succeeded(); - } } private void notifyFailure(Throwable failure) { - Callback callback; - synchronized (this) - { - callback = this.callback; - } + Callback callback = lock.runLocked(() -> this.callback); if (callback != null) - { callback.failed(failure); - } } } diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java index c3cca7ec1143..d11bb162b494 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java @@ -63,6 +63,7 @@ import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.component.LifeCycle; import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; @@ -249,7 +250,7 @@ public static String normalizeURI(String uri) */ public XmlConfiguration(Resource resource) throws SAXException, IOException { - synchronized (PARSER) + try (AutoLock ignored = PARSER.lock()) { _location = resource; try (InputStream inputStream = resource.getInputStream()) diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlParser.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlParser.java index 58f8da3c4881..007ab207b9cd 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlParser.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlParser.java @@ -35,6 +35,7 @@ import org.eclipse.jetty.util.LazyList; import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; @@ -56,17 +57,15 @@ public class XmlParser { private static final Logger LOG = LoggerFactory.getLogger(XmlParser.class); - private Map _redirectMap = new HashMap(); + private final AutoLock _lock = new AutoLock(); + private final Map _redirectMap = new HashMap<>(); + private final Stack _observers = new Stack<>(); private SAXParser _parser; private Map _observerMap; - private Stack _observers = new Stack(); private String _xpath; private Object _xpaths; private String _dtd; - /** - * Construct - */ public XmlParser() { SAXParserFactory factory = SAXParserFactory.newInstance(); @@ -81,6 +80,11 @@ public XmlParser(boolean validating) setValidating(validating); } + AutoLock lock() + { + return _lock.lock(); + } + public void setValidating(boolean validating) { try @@ -127,10 +131,10 @@ public boolean isValidating() return _parser.isValidating(); } - public synchronized void redirectEntity(String name, URL entity) + public void redirectEntity(String name, URL entity) { if (entity != null) - _redirectMap.put(name, entity); + _lock.runLocked(() -> _redirectMap.put(name, entity)); } /** @@ -170,29 +174,35 @@ public String getDTD() * @param trigger Tag local or q name. * @param observer SAX ContentHandler */ - public synchronized void addContentHandler(String trigger, ContentHandler observer) + public void addContentHandler(String trigger, ContentHandler observer) { - if (_observerMap == null) - _observerMap = new HashMap<>(); - _observerMap.put(trigger, observer); + try (AutoLock ignored = _lock.lock()) + { + if (_observerMap == null) + _observerMap = new HashMap<>(); + _observerMap.put(trigger, observer); + } } - public synchronized Node parse(InputSource source) throws IOException, SAXException + public Node parse(InputSource source) throws IOException, SAXException { - _dtd = null; - Handler handler = new Handler(); - XMLReader reader = _parser.getXMLReader(); - reader.setContentHandler(handler); - reader.setErrorHandler(handler); - reader.setEntityResolver(handler); - if (LOG.isDebugEnabled()) - LOG.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId()); - _parser.parse(source, handler); - if (handler._error != null) - throw handler._error; - Node doc = (Node)handler._top.get(0); - handler.clear(); - return doc; + try (AutoLock ignored = _lock.lock()) + { + _dtd = null; + Handler handler = new Handler(); + XMLReader reader = _parser.getXMLReader(); + reader.setContentHandler(handler); + reader.setErrorHandler(handler); + reader.setEntityResolver(handler); + if (LOG.isDebugEnabled()) + LOG.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId()); + _parser.parse(source, handler); + if (handler._error != null) + throw handler._error; + Node doc = (Node)handler._top.get(0); + handler.clear(); + return doc; + } } /** @@ -203,7 +213,7 @@ public synchronized Node parse(InputSource source) throws IOException, SAXExcept * @throws IOException if unable to load the xml * @throws SAXException if unable to parse the xml */ - public synchronized Node parse(String url) throws IOException, SAXException + public Node parse(String url) throws IOException, SAXException { if (LOG.isDebugEnabled()) LOG.debug("parse: " + url); @@ -218,7 +228,7 @@ public synchronized Node parse(String url) throws IOException, SAXException * @throws IOException if unable to load the xml * @throws SAXException if unable to parse the xml */ - public synchronized Node parse(File file) throws IOException, SAXException + public Node parse(File file) throws IOException, SAXException { if (LOG.isDebugEnabled()) LOG.debug("parse: " + file); @@ -233,20 +243,9 @@ public synchronized Node parse(File file) throws IOException, SAXException * @throws IOException if unable to load the xml * @throws SAXException if unable to parse the xml */ - public synchronized Node parse(InputStream in) throws IOException, SAXException + public Node parse(InputStream in) throws IOException, SAXException { - _dtd = null; - Handler handler = new Handler(); - XMLReader reader = _parser.getXMLReader(); - reader.setContentHandler(handler); - reader.setErrorHandler(handler); - reader.setEntityResolver(handler); - _parser.parse(new InputSource(in), handler); - if (handler._error != null) - throw handler._error; - Node doc = (Node)handler._top.get(0); - handler.clear(); - return doc; + return parse(new InputSource(in)); } protected InputSource resolveEntity(String pid, String sid) @@ -629,7 +628,7 @@ public Node get(String tag) public void add(int i, Object o) { if (_list == null) - _list = new ArrayList(); + _list = new ArrayList<>(); if (o instanceof String) { if (_lastString) @@ -676,7 +675,7 @@ public String getString(String tag, boolean tags, boolean trim) } @Override - public synchronized String toString() + public String toString() { return toString(true); } @@ -687,7 +686,7 @@ public synchronized String toString() * @param tag If false, only _content is shown. * @return the string value */ - public synchronized String toString(boolean tag) + public String toString(boolean tag) { StringBuilder buf = new StringBuilder(); toString(buf, tag); @@ -701,7 +700,7 @@ public synchronized String toString(boolean tag) * @param trim true to trim the content * @return the trimmed content */ - public synchronized String toString(boolean tag, boolean trim) + public String toString(boolean tag, boolean trim) { String s = toString(tag); if (s != null && trim) @@ -709,7 +708,7 @@ public synchronized String toString(boolean tag, boolean trim) return s; } - private synchronized void toString(StringBuilder buf, boolean tag) + private void toString(StringBuilder buf, boolean tag) { if (tag) { diff --git a/tests/jetty-http-tools/src/test/java/org/eclipse/jetty/http/tools/HttpTesterTest.java b/tests/jetty-http-tools/src/test/java/org/eclipse/jetty/http/tools/HttpTesterTest.java index c09db1f64977..0fce50844f89 100644 --- a/tests/jetty-http-tools/src/test/java/org/eclipse/jetty/http/tools/HttpTesterTest.java +++ b/tests/jetty-http-tools/src/test/java/org/eclipse/jetty/http/tools/HttpTesterTest.java @@ -256,7 +256,7 @@ public void testResponsesSplitInput() throws Exception PipedInputStream stream = new PipedInputStream(src) { @Override - public synchronized int read(byte[] b, int off, int len) throws IOException + public int read(byte[] b, int off, int len) throws IOException { if (available() == 0) return 0; diff --git a/tests/jetty-jmh/src/main/java/org/eclipse/jetty/util/jmh/DateCacheSimpleDateFormat.java b/tests/jetty-jmh/src/main/java/org/eclipse/jetty/util/jmh/DateCacheSimpleDateFormat.java index 1b6e8076480a..10430a84d801 100644 --- a/tests/jetty-jmh/src/main/java/org/eclipse/jetty/util/jmh/DateCacheSimpleDateFormat.java +++ b/tests/jetty-jmh/src/main/java/org/eclipse/jetty/util/jmh/DateCacheSimpleDateFormat.java @@ -23,6 +23,8 @@ import java.util.Locale; import java.util.TimeZone; +import org.eclipse.jetty.util.thread.AutoLock; + /** * Date Format Cache. * Computes String representations of Dates and caches @@ -40,14 +42,11 @@ */ public class DateCacheSimpleDateFormat { - public static final String DEFAULT_FORMAT = "EEE MMM dd HH:mm:ss zzz yyyy"; + private final AutoLock _lock = new AutoLock(); private final String _formatString; - private final String _tzFormatString; private final SimpleDateFormat _tzFormat; - private final Locale _locale; - private volatile Tick _tick; public static class Tick @@ -96,9 +95,9 @@ public DateCacheSimpleDateFormat(String format, Locale l, String tz) public DateCacheSimpleDateFormat(String format, Locale l, TimeZone tz) { _formatString = format; - _locale = l; int zIndex = _formatString.indexOf("ZZZ"); + String tzFormatString; if (zIndex >= 0) { final String ss1 = _formatString.substring(0, zIndex); @@ -129,19 +128,17 @@ public DateCacheSimpleDateFormat(String format, Locale l, TimeZone tz) sb.append('\''); sb.append(ss2); - _tzFormatString = sb.toString(); + tzFormatString = sb.toString(); } else - _tzFormatString = _formatString; - - if (_locale != null) { - _tzFormat = new SimpleDateFormat(_tzFormatString, _locale); + tzFormatString = _formatString; } + + if (l != null) + _tzFormat = new SimpleDateFormat(tzFormatString, l); else - { - _tzFormat = new SimpleDateFormat(_tzFormatString); - } + _tzFormat = new SimpleDateFormat(tzFormatString); _tzFormat.setTimeZone(tz); _tick = null; @@ -168,10 +165,7 @@ public String format(Date inDate) if (tick == null || seconds != tick._seconds) { // It's a cache miss - synchronized (this) - { - return _tzFormat.format(inDate); - } + return _lock.runLocked(() -> _tzFormat.format(inDate)); } return tick._string; @@ -196,10 +190,7 @@ public String format(long inDate) { // It's a cache miss Date d = new Date(inDate); - synchronized (this) - { - return _tzFormat.format(d); - } + return _lock.runLocked(() -> _tzFormat.format(d)); } return tick._string; @@ -241,7 +232,7 @@ protected Tick formatTick(long now) long seconds = now / 1000; // Synchronize to protect _tzFormat - synchronized (this) + try (AutoLock ignored = _lock.lock()) { // recheck the tick, to save multiple formats if (_tick == null || _tick._seconds != seconds) diff --git a/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/DispatchServlet.java b/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/DispatchServlet.java index b8938aa1baed..cce492612714 100644 --- a/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/DispatchServlet.java +++ b/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/DispatchServlet.java @@ -255,9 +255,4 @@ public String getServletInfo() { return "Include Servlet"; } - - @Override - public synchronized void destroy() - { - } } diff --git a/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/Dump.java b/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/Dump.java index cda240ce815b..8859cb69cb05 100644 --- a/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/Dump.java +++ b/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/Dump.java @@ -919,7 +919,7 @@ public String getServletInfo() } @Override - public synchronized void destroy() + public void destroy() { _timer.cancel(); } diff --git a/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/RegTest.java b/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/RegTest.java index 7db6bace9bec..ca23b1ab5322 100644 --- a/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/RegTest.java +++ b/tests/test-webapps/test-jetty-webapp/src/main/java/com/acme/RegTest.java @@ -164,11 +164,6 @@ public String getServletInfo() return "Rego Servlet"; } - @Override - public synchronized void destroy() - { - } - private String notag(String s) { if (s == null) From 089e51f0bc02b63490e1038e0ec23d1d43adf9a8 Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Wed, 29 Jul 2020 15:34:01 +0200 Subject: [PATCH 2/3] Fixes #5083 - Convert synchronized usages to AutoLock. Updates after review. Signed-off-by: Simone Bordet --- .../annotations/AnnotationIntrospector.java | 2 +- .../org/eclipse/jetty/client/HttpChannel.java | 9 +- .../eclipse/jetty/client/HttpConnection.java | 6 +- .../eclipse/jetty/client/HttpExchange.java | 39 +- .../eclipse/jetty/client/HttpReceiver.java | 9 +- .../jetty/client/MultiplexConnectionPool.java | 38 +- .../client/RoundRobinConnectionPool.java | 28 +- .../client/util/AsyncRequestContent.java | 20 +- .../jetty/deploy/DeploymentManager.java | 9 +- .../client/http/HttpConnectionOverFCGI.java | 7 +- .../eclipse/jetty/fcgi/generator/Flusher.java | 10 +- .../jetty/http2/client/RawHTTP2ProxyTest.java | 29 +- .../eclipse/jetty/http2/HTTP2Connection.java | 10 +- .../org/eclipse/jetty/http2/HTTP2Flusher.java | 22 +- .../org/eclipse/jetty/http2/HTTP2Session.java | 14 +- .../org/eclipse/jetty/http2/HTTP2Stream.java | 41 +- .../jetty/http2/HTTP2StreamEndPoint.java | 23 +- .../client/http/HttpReceiverOverHTTP2.java | 15 +- .../http2/server/HTTP2ServerConnection.java | 16 +- .../http2/server/HttpTransportOverHTTP2.java | 14 +- .../eclipse/jetty/io/ByteArrayEndPoint.java | 24 +- .../org/eclipse/jetty/io/ManagedSelector.java | 17 +- .../jetty/io/SocketChannelEndPoint.java | 6 +- .../eclipse/jetty/io/ssl/SslConnection.java | 29 +- .../org/eclipse/jetty/jaas/spi/UserInfo.java | 8 +- .../eclipse/jetty/jndi/ContextFactory.java | 40 +- .../authentication/DigestAuthenticator.java | 2 +- .../jetty/server/AbstractConnector.java | 23 +- .../eclipse/jetty/server/AcceptRateLimit.java | 11 +- .../eclipse/jetty/server/ConnectionLimit.java | 29 +- .../jetty/server/HttpChannelState.java | 139 +++-- .../org/eclipse/jetty/server/HttpInput.java | 67 ++- .../org/eclipse/jetty/server/HttpOutput.java | 55 +- .../server/MultiPartFormInputStream.java | 38 +- .../jetty/server/RequestLogWriter.java | 8 +- .../eclipse/jetty/server/ResourceService.java | 25 +- .../eclipse/jetty/server/ShutdownMonitor.java | 63 +- .../jetty/server/handler/ContextHandler.java | 113 ++-- .../session/DefaultSessionIdManager.java | 6 +- .../jetty/server/session/HouseKeeper.java | 6 +- .../eclipse/jetty/server/session/Session.java | 104 ++-- .../server/ServerConnectorTimeoutTest.java | 15 +- .../org/eclipse/jetty/servlet/BaseHolder.java | 14 +- .../eclipse/jetty/servlet/FilterHolder.java | 4 +- .../org/eclipse/jetty/servlet/Holder.java | 2 +- .../org/eclipse/jetty/servlet/Invoker.java | 4 +- .../eclipse/jetty/servlet/ListenerHolder.java | 2 +- .../eclipse/jetty/servlet/ServletHandler.java | 298 ++++----- .../eclipse/jetty/servlet/ServletHolder.java | 32 +- .../org/eclipse/jetty/servlets/DoSFilter.java | 4 +- .../jetty/servlets/EventSourceServlet.java | 17 +- .../jetty/util/ajax/JSONDateConvertor.java | 2 +- .../jetty/util/RolloverFileOutputStream.java | 12 +- .../java/org/eclipse/jetty/util/Scanner.java | 51 +- .../org/eclipse/jetty/util/StringUtil.java | 13 +- .../java/org/eclipse/jetty/util/URIUtil.java | 31 +- .../org/eclipse/jetty/util/UrlEncoded.java | 565 +++++++++--------- .../util/component/AbstractLifeCycle.java | 4 +- .../util/component/AttributeContainerMap.java | 21 +- .../jetty/util/resource/JarFileResource.java | 8 +- .../jetty/util/resource/JarResource.java | 4 +- .../jetty/util/resource/URLResource.java | 8 +- .../jetty/util/security/Credential.java | 37 +- .../jetty/util/ssl/SslContextFactory.java | 12 +- .../jetty/util/statistic/RateStatistic.java | 24 +- .../eclipse/jetty/util/thread/AutoLock.java | 45 +- .../jetty/util/thread/QueuedThreadPool.java | 8 +- .../jetty/util/thread/ShutdownThread.java | 47 +- .../util/thread/strategy/EatWhatYouKill.java | 22 +- .../eclipse/jetty/webapp/Configurations.java | 64 +- .../org/eclipse/jetty/webapp/MetaData.java | 2 +- .../jetty/webapp/ConfigurationsTest.java | 4 +- .../jetty/webapp/WebAppContextTest.java | 8 +- .../websocket/core/internal/FrameFlusher.java | 18 +- .../core/internal/FrameSequence.java | 2 +- .../core/internal/TransformingFlusher.java | 9 +- .../core/internal/WebSocketConnection.java | 19 +- .../core/internal/WebSocketSessionState.java | 24 +- .../common/JavaxWebSocketFrameHandler.java | 36 +- .../common/JettyWebSocketFrameHandler.java | 15 +- .../util/messages/MessageInputStream.java | 10 +- .../util/messages/MessageOutputStream.java | 21 +- .../eclipse/jetty/xml/XmlConfiguration.java | 2 +- .../java/org/eclipse/jetty/xml/XmlParser.java | 20 +- .../jetty/http/tools/HttpTesterTest.java | 2 +- .../util/jmh/DateCacheSimpleDateFormat.java | 30 +- 86 files changed, 1608 insertions(+), 1158 deletions(-) diff --git a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java index aed655445f3c..b49d663a7c10 100644 --- a/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java +++ b/jetty-annotations/src/main/java/org/eclipse/jetty/annotations/AnnotationIntrospector.java @@ -198,7 +198,7 @@ public void introspect(Object o, Object metaInfo) Class clazz = o.getClass(); - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // Lock to ensure that only 1 thread can be introspecting, and that // thread must have fully finished generating the products of diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java index 7f1519a3270a..99485134601b 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpChannel.java @@ -60,7 +60,7 @@ public boolean associate(HttpExchange exchange) { boolean result = false; boolean abort = true; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_exchange == null) { @@ -87,7 +87,7 @@ public boolean associate(HttpExchange exchange) public boolean disassociate(HttpExchange exchange) { boolean result = false; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { HttpExchange existing = _exchange; _exchange = null; @@ -105,7 +105,10 @@ public boolean disassociate(HttpExchange exchange) public HttpExchange getHttpExchange() { - return _lock.runLocked(() -> _exchange); + try (AutoLock l = _lock.lock()) + { + return _exchange; + } } protected abstract HttpSender getHttpSender(); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java index f3c0e136d293..9abc17bce8e3 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpConnection.java @@ -89,7 +89,7 @@ protected SendFailure send(HttpChannel channel, HttpExchange exchange) // the request is associated to the channel and sent. // Use a counter to support multiplexed requests. boolean send; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { send = idleTimeoutGuard >= 0; if (send) @@ -113,7 +113,7 @@ protected SendFailure send(HttpChannel channel, HttpExchange exchange) result = new SendFailure(new HttpRequestException("Could not associate request to connection", request), false); } - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { --idleTimeoutGuard; idleTimeoutStamp = System.nanoTime(); @@ -252,7 +252,7 @@ private void applyRequestAuthentication(Request request) public boolean onIdleTimeout(long idleTimeout) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (idleTimeoutGuard == 0) { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java index 01b81fcc2dbd..d79eed6f253e 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpExchange.java @@ -70,7 +70,10 @@ public HttpRequest getRequest() public Throwable getRequestFailure() { - return lock.runLocked(() -> requestFailure); + try (AutoLock l = lock.lock()) + { + return requestFailure; + } } public List getResponseListeners() @@ -85,7 +88,10 @@ public HttpResponse getResponse() public Throwable getResponseFailure() { - return lock.runLocked(() -> responseFailure); + try (AutoLock l = lock.lock()) + { + return responseFailure; + } } /** @@ -99,7 +105,7 @@ boolean associate(HttpChannel channel) { boolean result = false; boolean abort = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { // Only associate if the exchange state is initial, // as the exchange could be already failed. @@ -123,7 +129,7 @@ boolean associate(HttpChannel channel) void disassociate(HttpChannel channel) { boolean abort = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (_channel != channel || requestState != State.TERMINATED || responseState != State.TERMINATED) abort = true; @@ -136,12 +142,18 @@ void disassociate(HttpChannel channel) private HttpChannel getHttpChannel() { - return lock.runLocked(() -> _channel); + try (AutoLock l = lock.lock()) + { + return _channel; + } } public boolean requestComplete(Throwable failure) { - return lock.runLocked(() -> completeRequest(failure)); + try (AutoLock l = lock.lock()) + { + return completeRequest(failure); + } } private boolean completeRequest(Throwable failure) @@ -157,7 +169,10 @@ private boolean completeRequest(Throwable failure) public boolean responseComplete(Throwable failure) { - return lock.runLocked(() -> completeResponse(failure)); + try (AutoLock l = lock.lock()) + { + return completeResponse(failure); + } } private boolean completeResponse(Throwable failure) @@ -174,7 +189,7 @@ private boolean completeResponse(Throwable failure) public Result terminateRequest() { Result result = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (requestState == State.COMPLETED) requestState = State.TERMINATED; @@ -191,7 +206,7 @@ public Result terminateRequest() public Result terminateResponse() { Result result = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (responseState == State.COMPLETED) responseState = State.TERMINATED; @@ -211,7 +226,7 @@ public boolean abort(Throwable failure) // This will avoid that this exchange can be associated to a channel. boolean abortRequest; boolean abortResponse; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { abortRequest = completeRequest(failure); abortResponse = completeResponse(failure); @@ -270,7 +285,7 @@ private void notifyFailureComplete(Throwable failure) public void resetResponse() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { responseState = State.PENDING; responseFailure = null; @@ -287,7 +302,7 @@ public void proceed(Throwable failure) @Override public String toString() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { return String.format("%s@%x req=%s/%s@%h res=%s/%s@%h", HttpExchange.class.getSimpleName(), diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java index 6325c01864c5..2466f6ed59bd 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/HttpReceiver.java @@ -100,7 +100,7 @@ void demand(long n) throw new IllegalArgumentException("Invalid demand " + n); boolean resume = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { demand = MathUtils.cappedAdd(demand, n); if (stalled) @@ -128,12 +128,15 @@ protected long demand() private long demand(LongUnaryOperator operator) { - return lock.runLocked(() -> demand = operator.applyAsLong(demand)); + try (AutoLock l = lock.lock()) + { + return demand = operator.applyAsLong(demand); + } } protected boolean hasDemandOrStall() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { stalled = demand <= 0; return !stalled; diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java index d2034866470b..364a63dcfe11 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/MultiplexConnectionPool.java @@ -82,13 +82,19 @@ private static int ceilDiv(int a, int b) @Override public int getMaxMultiplex() { - return lock.runLocked(() -> maxMultiplex); + try (AutoLock l = lock.lock()) + { + return maxMultiplex; + } } @Override public void setMaxMultiplex(int maxMultiplex) { - lock.runLocked(() -> this.maxMultiplex = maxMultiplex); + try (AutoLock l = lock.lock()) + { + this.maxMultiplex = maxMultiplex; + } } @Override @@ -99,7 +105,7 @@ public boolean accept(Connection connection) LOG.debug("Accepted {} {}", accepted, connection); if (accepted) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { Holder holder = new Holder(connection); activeConnections.put(connection, holder); @@ -113,14 +119,20 @@ public boolean accept(Connection connection) @Override public boolean isActive(Connection connection) { - return lock.runLocked(() -> activeConnections.containsKey(connection)); + try (AutoLock l = lock.lock()) + { + return activeConnections.containsKey(connection); + } } @Override protected void onCreated(Connection connection) { - // Use "cold" connections as last. - lock.runLocked(() -> idleConnections.offer(new Holder(connection))); + try (AutoLock l = lock.lock()) + { + // Use "cold" connections as last. + idleConnections.offer(new Holder(connection)); + } idle(connection, false); } @@ -128,7 +140,7 @@ protected void onCreated(Connection connection) protected Connection activate() { Holder result = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { for (Holder holder : activeConnections.values()) { @@ -159,7 +171,7 @@ public boolean release(Connection connection) boolean closed = isClosed(); boolean idle = false; Holder holder; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { holder = activeConnections.get(connection); if (holder != null) @@ -195,7 +207,7 @@ protected boolean remove(Connection connection, boolean force) { boolean activeRemoved = true; boolean idleRemoved = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { Holder holder = activeConnections.remove(connection); if (holder == null) @@ -226,7 +238,7 @@ public void close() { super.close(); List connections; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { connections = idleConnections.stream().map(holder -> holder.connection).collect(Collectors.toList()); connections.addAll(activeConnections.keySet()); @@ -239,7 +251,7 @@ public void dump(Appendable out, String indent) throws IOException { DumpableCollection active; DumpableCollection idle; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { active = new DumpableCollection("active", new ArrayList<>(activeConnections.values())); idle = new DumpableCollection("idle", new ArrayList<>(idleConnections)); @@ -251,7 +263,7 @@ public void dump(Appendable out, String indent) throws IOException public boolean sweep() { List toSweep = new ArrayList<>(); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { activeConnections.values().stream() .map(holder -> holder.connection) @@ -279,7 +291,7 @@ public String toString() { int activeSize; int idleSize; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { activeSize = activeConnections.size(); idleSize = idleConnections.size(); diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java b/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java index c45bad9115cf..dbf8bde4699c 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/RoundRobinConnectionPool.java @@ -55,13 +55,19 @@ public RoundRobinConnectionPool(HttpDestination destination, int maxConnections, @Override public int getMaxMultiplex() { - return lock.runLocked(() -> maxMultiplex); + try (AutoLock l = lock.lock()) + { + return maxMultiplex; + } } @Override public void setMaxMultiplex(int maxMultiplex) { - lock.runLocked(() -> this.maxMultiplex = maxMultiplex); + try (AutoLock l = lock.lock()) + { + this.maxMultiplex = maxMultiplex; + } } /** @@ -82,7 +88,7 @@ public Connection acquire(boolean create) @Override protected void onCreated(Connection connection) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { for (Entry entry : entries) { @@ -100,7 +106,7 @@ protected void onCreated(Connection connection) protected Connection activate() { Connection connection = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { int offset = 0; int capacity = getMaxConnectionCount(); @@ -135,7 +141,7 @@ protected Connection activate() @Override public boolean isActive(Connection connection) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { for (Entry entry : entries) { @@ -151,7 +157,7 @@ public boolean release(Connection connection) { boolean found = false; boolean idle = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { for (Entry entry : entries) { @@ -176,7 +182,7 @@ public boolean release(Connection connection) public boolean remove(Connection connection) { boolean found = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { for (Entry entry : entries) { @@ -199,7 +205,11 @@ public boolean remove(Connection connection) @Override public void dump(Appendable out, String indent) throws IOException { - List connections = lock.runLocked(() -> new ArrayList<>(entries)); + List connections; + try (AutoLock l = lock.lock()) + { + connections = new ArrayList<>(entries); + } Dumpable.dumpObjects(out, indent, out, connections); } @@ -208,7 +218,7 @@ public String toString() { int present = 0; int active = 0; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { for (Entry entry : entries) { diff --git a/jetty-client/src/main/java/org/eclipse/jetty/client/util/AsyncRequestContent.java b/jetty-client/src/main/java/org/eclipse/jetty/client/util/AsyncRequestContent.java index 79ac545212e3..e832bfe2d54c 100644 --- a/jetty-client/src/main/java/org/eclipse/jetty/client/util/AsyncRequestContent.java +++ b/jetty-client/src/main/java/org/eclipse/jetty/client/util/AsyncRequestContent.java @@ -27,6 +27,7 @@ import java.util.Deque; import java.util.List; import java.util.Objects; +import java.util.concurrent.locks.Condition; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -41,7 +42,8 @@ public class AsyncRequestContent implements Request.Content, Request.Content.Sub { private static final Logger LOG = LoggerFactory.getLogger(AsyncRequestContent.class); - private final AutoLock.WithCondition lock = new AutoLock.WithCondition(); + private final AutoLock lock = new AutoLock(); + private final Condition flush = lock.newCondition(); private final Deque chunks = new ArrayDeque<>(); private final String contentType; private long length = -1; @@ -116,7 +118,7 @@ public void demand() public void fail(Throwable failure) { List toFail = List.of(); - try (AutoLock.WithCondition l = lock.lock()) + try (AutoLock l = lock.lock()) { if (this.failure == null) { @@ -126,7 +128,7 @@ public void fail(Throwable failure) .map(chunk -> chunk.callback) .collect(Collectors.toList()); chunks.clear(); - l.signal(); + flush.signal(); } } toFail.forEach(c -> c.failed(failure)); @@ -291,15 +293,15 @@ private void notifyFailure(Consumer consumer, Throwable failure) private void notifyFlush() { - try (AutoLock.WithCondition l = lock.lock()) + try (AutoLock l = lock.lock()) { - l.signal(); + flush.signal(); } } public void flush() throws IOException { - try (AutoLock.WithCondition l = lock.lock()) + try (AutoLock l = lock.lock()) { try { @@ -311,7 +313,7 @@ public void flush() throws IOException throw new IOException(failure); if (chunks.isEmpty()) return; - l.await(); + flush.await(); } } catch (InterruptedException x) @@ -325,7 +327,7 @@ public void flush() throws IOException public void close() { boolean produce = false; - try (AutoLock.WithCondition l = lock.lock()) + try (AutoLock l = lock.lock()) { if (closed) return; @@ -338,7 +340,7 @@ public void close() produce = true; } } - l.signal(); + flush.signal(); } if (produce) produce(); diff --git a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java index b8565032e874..04c4bd901434 100644 --- a/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java +++ b/jetty-deploy/src/main/java/org/eclipse/jetty/deploy/DeploymentManager.java @@ -47,6 +47,7 @@ import org.eclipse.jetty.util.annotation.Name; import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.resource.Resource; +import org.eclipse.jetty.util.thread.AutoLock; import org.eclipse.jetty.xml.XmlConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -125,6 +126,7 @@ void setLifeCycleNode(Node node) } } + private final AutoLock _lock = new AutoLock(); private final List _providers = new ArrayList(); private final AppLifeCycle _lifecycle = new AppLifeCycle(); private final Queue _apps = new ConcurrentLinkedQueue(); @@ -564,11 +566,12 @@ public void requestAppGoal(@Name("appId") String appId, @Name("nodeName") String private void addOnStartupError(Throwable cause) { - if (onStartupErrors == null) + try (AutoLock l = _lock.lock()) { - onStartupErrors = new MultiException(); + if (onStartupErrors == null) + onStartupErrors = new MultiException(); + onStartupErrors.add(cause); } - onStartupErrors.add(cause); } /** diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java index 9a5d950c28a1..01f971a32e89 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/client/http/HttpConnectionOverFCGI.java @@ -309,7 +309,7 @@ private void failAndClose(Throwable failure) private int acquireRequest() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { int last = requests.getLast(); int request = last + 1; @@ -320,7 +320,10 @@ private int acquireRequest() private void releaseRequest(int request) { - lock.runLocked(() -> requests.removeFirstOccurrence(request)); + try (AutoLock l = lock.lock()) + { + requests.removeFirstOccurrence(request); + } } protected HttpChannelOverFCGI acquireHttpChannel(int id, Request request) diff --git a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java index 66283bc28e13..9263cbb44500 100644 --- a/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java +++ b/jetty-fcgi/fcgi-client/src/main/java/org/eclipse/jetty/fcgi/generator/Flusher.java @@ -53,12 +53,18 @@ public void flush(Generator.Result... results) private void offer(Generator.Result result) { - lock.runLocked(() -> queue.offer(result)); + try (AutoLock l = lock.lock()) + { + queue.offer(result); + } } private Generator.Result poll() { - return lock.runLocked(queue::poll); + try (AutoLock l = lock.lock()) + { + return queue.poll(); + } } public void shutdown() diff --git a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java index 58a7484189ca..49bc7131ebdd 100644 --- a/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java +++ b/jetty-http2/http2-client/src/test/java/org/eclipse/jetty/http2/client/RawHTTP2ProxyTest.java @@ -340,7 +340,7 @@ private void offer(Stream stream, Frame frame, Callback callback) if (LOGGER.isDebugEnabled()) LOGGER.debug("CPS queueing {} for {} on {}", frame, stream, stream.getSession()); boolean connected; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { Deque deque = frames.computeIfAbsent(stream, s -> new ArrayDeque<>()); deque.offer(new FrameInfo(frame, callback)); @@ -364,7 +364,10 @@ public void succeeded(Session result) { if (LOGGER.isDebugEnabled()) LOGGER.debug("CPS connected to {} with {}", address, result); - lock.runLocked(() -> proxyToServerSession = result); + try (AutoLock l = lock.lock()) + { + proxyToServerSession = result; + } iterate(); } @@ -383,7 +386,7 @@ protected Action process() throws Throwable { Stream proxyToServerStream = null; Session proxyToServerSession = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { for (Map.Entry> entry : frames.entrySet()) { @@ -413,9 +416,12 @@ protected Action process() throws Throwable @Override public void succeeded(Stream result) { - if (LOGGER.isDebugEnabled()) - LOGGER.debug("CPS created {}", result); - lock.runLocked(() -> streams.put(clientToProxyStream, result)); + try (AutoLock l = lock.lock()) + { + if (LOGGER.isDebugEnabled()) + LOGGER.debug("CPS created {}", result); + streams.put(clientToProxyStream, result); + } serverToProxyToClient.link(result, clientToProxyStream); ClientToProxyToServer.this.succeeded(); } @@ -551,10 +557,10 @@ private static class ServerToProxyToClient extends IteratingCallback implements private Stream serverToProxyStream; @Override - protected Action process() + protected Action process() throws Throwable { Stream proxyToClientStream = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { for (Map.Entry> entry : frames.entrySet()) { @@ -625,7 +631,7 @@ private void offer(Stream stream, Frame frame, Callback callback) { if (LOGGER.isDebugEnabled()) LOGGER.debug("SPC queueing {} for {} on {}", frame, stream, stream.getSession()); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { Deque deque = frames.computeIfAbsent(stream, s -> new ArrayDeque<>()); deque.offer(new FrameInfo(frame, callback)); @@ -677,7 +683,10 @@ public boolean onIdleTimeout(Stream stream, Throwable x) private void link(Stream proxyToServerStream, Stream clientToProxyStream) { - lock.runLocked(() -> streams.put(proxyToServerStream, clientToProxyStream)); + try (AutoLock l = lock.lock()) + { + streams.put(proxyToServerStream, clientToProxyStream); + } iterate(); } } diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java index b0cdbbf5a50a..f06f4d936ff8 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Connection.java @@ -192,7 +192,10 @@ protected void offerTask(Runnable task, boolean dispatch) private void offerTask(Runnable task) { - lock.runLocked(() -> tasks.offer(task)); + try (AutoLock l = lock.lock()) + { + tasks.offer(task); + } } protected void produce() @@ -219,7 +222,10 @@ public void close() private Runnable pollTask() { - return lock.runLocked(tasks::poll); + try (AutoLock l = lock.lock()) + { + return tasks.poll(); + } } @Override diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java index b87e5f711e06..8d2044f92b77 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Flusher.java @@ -66,7 +66,7 @@ public HTTP2Flusher(HTTP2Session session) public void window(IStream stream, WindowUpdateFrame frame) { Throwable closed; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { closed = terminated; if (closed == null) @@ -80,7 +80,7 @@ public void window(IStream stream, WindowUpdateFrame frame) public boolean prepend(Entry entry) { Throwable closed; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { closed = terminated; if (closed == null) @@ -99,7 +99,7 @@ public boolean prepend(Entry entry) public boolean append(Entry entry) { Throwable closed; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { closed = terminated; if (closed == null) @@ -117,12 +117,18 @@ public boolean append(Entry entry) private int getWindowQueueSize() { - return lock.runLocked(windows::size); + try (AutoLock l = lock.lock()) + { + return windows.size(); + } } public int getFrameQueueSize() { - return lock.runLocked(entries::size); + try (AutoLock l = lock.lock()) + { + return entries.size(); + } } @Override @@ -131,7 +137,7 @@ protected Action process() throws Throwable if (LOG.isDebugEnabled()) LOG.debug("Flushing {}", session); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (terminated != null) throw terminated; @@ -319,7 +325,7 @@ protected void onCompleteFailure(Throwable x) Throwable closed; Set allEntries; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { closed = terminated; terminated = x; @@ -348,7 +354,7 @@ protected void onCompleteFailure(Throwable x) void terminate(Throwable cause) { Throwable closed; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { closed = terminated; terminated = cause; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java index 597938b15730..9169fd2cb0bb 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Session.java @@ -1827,7 +1827,7 @@ private int reserveSlot(Slot slot, int streamId) { if (streamId <= 0) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { streamId = localStreamIds.getAndAdd(2); slots.offer(slot); @@ -1835,14 +1835,20 @@ private int reserveSlot(Slot slot, int streamId) } else { - lock.runLocked(() -> slots.offer(slot)); + try (AutoLock l = lock.lock()) + { + slots.offer(slot); + } } return streamId; } private void releaseSlotFlushAndFail(Slot slot, Promise promise, Throwable x) { - lock.runLocked(() -> slots.remove(slot)); + try (AutoLock l = lock.lock()) + { + slots.remove(slot); + } flush(); promise.failed(x); } @@ -1866,7 +1872,7 @@ private void flush() while (true) { ControlEntry entry; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (flushing == null) flushing = thread; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java index ac24709793a1..d31d716d66ef 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2Stream.java @@ -143,7 +143,7 @@ public void data(DataFrame frame, Callback callback) @Override public void reset(ResetFrame frame, Callback callback) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (isReset()) return; @@ -156,7 +156,7 @@ public void reset(ResetFrame frame, Callback callback) private boolean startWrite(Callback callback) { Throwable failure; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { failure = this.failure; if (failure == null && sendCallback == null) @@ -192,18 +192,27 @@ public Object removeAttribute(String key) @Override public boolean isReset() { - return lock.runLocked(() -> localReset || remoteReset); + try (AutoLock l = lock.lock()) + { + return localReset || remoteReset; + } } private boolean isFailed() { - return lock.runLocked(() -> failure != null); + try (AutoLock l = lock.lock()) + { + return failure != null; + } } @Override public boolean isResetOrFailed() { - return lock.runLocked(() -> isReset() || isFailed()); + try (AutoLock l = lock.lock()) + { + return isReset() || isFailed(); + } } @Override @@ -382,7 +391,7 @@ private void onData(DataFrame frame, Callback callback) boolean initial; boolean proceed = false; DataEntry entry = new DataEntry(frame, callback); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { dataQueue.offer(entry); initial = dataInitial; @@ -403,7 +412,7 @@ else if (!dataProcess) if (LOG.isDebugEnabled()) LOG.debug("Starting data processing of {} for {}", frame, this); notifyBeforeData(this); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { dataProcess = proceed = dataDemand > 0; } @@ -421,7 +430,7 @@ public void demand(long n) throw new IllegalArgumentException("Invalid demand " + n); long demand; boolean proceed = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { demand = dataDemand = MathUtils.cappedAdd(dataDemand, n); if (!dataProcess) @@ -438,7 +447,7 @@ private void processData() while (true) { DataEntry dataEntry; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (dataQueue.isEmpty() || dataDemand == 0) { @@ -459,12 +468,15 @@ private void processData() private long demand() { - return lock.runLocked(() -> dataDemand); + try (AutoLock l = lock.lock()) + { + return dataDemand; + } } private void onReset(ResetFrame frame, Callback callback) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { remoteReset = true; failure = new EofException("reset"); @@ -489,7 +501,10 @@ private void onWindowUpdate(WindowUpdateFrame frame, Callback callback) private void onFailure(FailureFrame frame, Callback callback) { - lock.runLocked(() -> failure = frame.getFailure()); + try (AutoLock l = lock.lock()) + { + failure = frame.getFailure(); + } close(); session.removeStream(this); notifyFailure(this, frame, callback); @@ -674,7 +689,7 @@ public void failed(Throwable x) private Callback endWrite() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { Callback callback = sendCallback; sendCallback = null; diff --git a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2StreamEndPoint.java b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2StreamEndPoint.java index e60525ad3e04..0251f7206724 100644 --- a/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2StreamEndPoint.java +++ b/jetty-http2/http2-common/src/main/java/org/eclipse/jetty/http2/HTTP2StreamEndPoint.java @@ -173,7 +173,11 @@ public void close(Throwable cause) @Override public int fill(ByteBuffer sink) throws IOException { - Entry entry = lock.runLocked(dataQueue::poll); + Entry entry; + try (AutoLock l = lock.lock()) + { + entry = dataQueue.poll(); + } if (LOG.isDebugEnabled()) LOG.debug("filled {} on {}", entry, this); @@ -204,7 +208,10 @@ public int fill(ByteBuffer sink) throws IOException if (source.hasRemaining()) { - lock.runLocked(() -> dataQueue.offerFirst(entry)); + try (AutoLock l = lock.lock()) + { + dataQueue.offerFirst(entry); + } } else { @@ -543,13 +550,19 @@ protected void offerFailure(Throwable failure) private void offer(ByteBuffer buffer, Callback callback, Throwable failure) { - Entry entry = new Entry(buffer, callback, failure); - lock.runLocked(() -> dataQueue.offer(entry)); + try (AutoLock l = lock.lock()) + { + dataQueue.offer(new Entry(buffer, callback, failure)); + } } protected void process() { - boolean empty = lock.runLocked(dataQueue::isEmpty); + boolean empty; + try (AutoLock l = lock.lock()) + { + empty = dataQueue.isEmpty(); + } if (!empty) { Callback callback = readCallback.getAndSet(null); diff --git a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java index 24ac5ef4938c..b55924a5dfb0 100644 --- a/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java +++ b/jetty-http2/http2-http-client-transport/src/main/java/org/eclipse/jetty/http2/client/http/HttpReceiverOverHTTP2.java @@ -271,7 +271,10 @@ private void offer(HttpExchange exchange, DataFrame frame, Callback callback) private void enqueue(DataInfo dataInfo) { - lock.runLocked(() -> queue.offer(dataInfo)); + try (AutoLock l = lock.lock()) + { + queue.offer(dataInfo); + } } private void process(boolean resume) @@ -284,7 +287,7 @@ private void process(boolean resume) return; // Process only if there is demand. - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (!resume && demand() <= 0) { @@ -308,7 +311,7 @@ private void process(boolean resume) } } - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { dataInfo = queue.poll(); if (LOG.isDebugEnabled()) @@ -346,7 +349,7 @@ private void process(boolean resume) private boolean active(boolean resume) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (active) { @@ -379,7 +382,7 @@ private boolean active(boolean resume) */ private boolean stall() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (resume) { @@ -399,7 +402,7 @@ private boolean stall() private void reset() { dataInfo = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { queue.clear(); active = false; diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java index 7143d43c5214..9bcf82d4bd0c 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HTTP2ServerConnection.java @@ -288,15 +288,27 @@ protected ServerHttpChannelOverHTTP2 newServerHttpChannelOverHTTP2(Connector con private void offerHttpChannel(HttpChannelOverHTTP2 channel) { if (isRecycleHttpChannels()) - lock.runLocked(() -> channels.offer(channel)); + { + try (AutoLock l = lock.lock()) + { + channels.offer(channel); + } + } } private HttpChannelOverHTTP2 pollHttpChannel() { if (isRecycleHttpChannels()) - return lock.runLocked(channels::poll); + { + try (AutoLock l = lock.lock()) + { + return channels.poll(); + } + } else + { return null; + } } public boolean upgrade(Request request, HttpFields.Mutable responseFields) diff --git a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java index 057bac13eb8f..b12a47d470d3 100644 --- a/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java +++ b/jetty-http2/http2-server/src/main/java/org/eclipse/jetty/http2/server/HttpTransportOverHTTP2.java @@ -445,7 +445,7 @@ private void abort(Throwable failure) private Throwable sending(Callback callback, boolean commit) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { switch (_state) { @@ -473,7 +473,7 @@ public void succeeded() { Callback callback; boolean commit; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_state != State.SENDING) { @@ -497,7 +497,7 @@ public void failed(Throwable failure) { Callback callback; boolean commit; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_state != State.SENDING) { @@ -519,7 +519,7 @@ public void failed(Throwable failure) private boolean idleTimeout(Throwable failure) { Callback callback = null; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // Ignore idle timeouts if not writing, // as the application may be suspended. @@ -543,7 +543,11 @@ private boolean idleTimeout(Throwable failure) @Override public InvocationType getInvocationType() { - Callback callback = _lock.runLocked(() -> _callback); + Callback callback; + try (AutoLock l = _lock.lock()) + { + callback = _callback; + } return callback != null ? callback.getInvocationType() : Callback.super.getInvocationType(); } } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java index 3975fcccd084..c360152cf1cf 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ByteArrayEndPoint.java @@ -31,6 +31,7 @@ import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.thread.AutoLock; @@ -68,7 +69,8 @@ public class ByteArrayEndPoint extends AbstractEndPoint private static final ByteBuffer EOF = BufferUtil.allocate(0); private final Runnable _runFillable = () -> getFillInterest().fillable(); - private final AutoLock.WithCondition _lock = new AutoLock.WithCondition(); + private final AutoLock _lock = new AutoLock(); + private final Condition _hasOutput = _lock.newCondition(); private final Queue _inQ = new ArrayDeque<>(); private ByteBuffer _out; private boolean _growOutput; @@ -125,9 +127,9 @@ public ByteArrayEndPoint(Scheduler timer, long idleTimeoutMs, ByteBuffer input, public void doShutdownOutput() { super.doShutdownOutput(); - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { - lock.signalAll(); + _hasOutput.signalAll(); } } @@ -135,9 +137,9 @@ public void doShutdownOutput() public void doClose() { super.doClose(); - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { - lock.signalAll(); + _hasOutput.signalAll(); } } @@ -301,11 +303,11 @@ public ByteBuffer waitForOutput(long time, TimeUnit unit) throws InterruptedExce { ByteBuffer b; - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { while (BufferUtil.isEmpty(_out) && !isOutputShutdown()) { - if (!lock.await(time, unit)) + if (!_hasOutput.await(time, unit)) return null; } b = _out; @@ -399,7 +401,7 @@ else if (filled < 0) public boolean flush(ByteBuffer... buffers) throws IOException { boolean flushed = true; - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (!isOpen()) throw new IOException("CLOSED"); @@ -436,7 +438,7 @@ public boolean flush(ByteBuffer... buffers) throws IOException if (!idle) { notIdle(); - lock.signalAll(); + _hasOutput.signalAll(); } } return flushed; @@ -445,11 +447,11 @@ public boolean flush(ByteBuffer... buffers) throws IOException @Override public void reset() { - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { _inQ.clear(); + _hasOutput.signalAll(); BufferUtil.clear(_out); - lock.signalAll(); } super.reset(); } diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java index 4f856097ec93..78f52e3e2084 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ManagedSelector.java @@ -254,7 +254,7 @@ private void submit(SelectorUpdate update, boolean lazy) LOG.debug("Queued change lazy={} {} on {}", lazy, update, this); Selector selector = null; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _updates.offer(update); @@ -280,7 +280,7 @@ private void wakeup() LOG.debug("Wakeup {}", this); Selector selector = null; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_selecting) { @@ -384,7 +384,10 @@ void destroyEndPoint(EndPoint endPoint, Throwable cause) private int getActionSize() { - return _lock.runLocked(() -> _updates.size()); + try (AutoLock l = _lock.lock()) + { + return _updates.size(); + } } static int safeReadyOps(SelectionKey selectionKey) @@ -423,7 +426,7 @@ public void dump(Appendable out, String indent) throws IOException { DumpKeys dump = new DumpKeys(); String updatesAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()); - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { updates = new ArrayList<>(_updates); _updates.addFirst(dump); @@ -513,7 +516,7 @@ public Runnable produce() private void processUpdates() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { Deque updates = _updates; _updates = _updateable; @@ -542,7 +545,7 @@ private void processUpdates() Selector selector; int updates; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { updates = _updates.size(); _selecting = updates == 0; @@ -578,7 +581,7 @@ private boolean select() LOG.debug("Selector {} woken up from select, {}/{}/{} selected", selector, selected, selector.selectedKeys().size(), selector.keys().size()); int updates; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // finished selecting _selecting = false; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java b/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java index 3d4ce44c6654..67b2141b0483 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/SocketChannelEndPoint.java @@ -319,7 +319,7 @@ public Runnable onSelected() int readyOps = _key.readyOps(); int oldInterestOps; int newInterestOps; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _updatePending = true; // Remove the readyOps, that here can only be OP_READ or OP_WRITE (or both). @@ -363,7 +363,7 @@ public void updateKey() { int oldInterestOps; int newInterestOps; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _updatePending = false; oldInterestOps = _currentInterestOps; @@ -405,7 +405,7 @@ private void changeInterests(int operation) int oldInterestOps; int newInterestOps; boolean pending; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { pending = _updatePending; oldInterestOps = _desiredInterestOps; diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java index f771c08f6e86..8c1cb69e4764 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/ssl/SslConnection.java @@ -516,7 +516,7 @@ protected void onFillable() { // If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read boolean waitingForFill; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("onFillable {}", SslConnection.this); @@ -529,7 +529,10 @@ protected void onFillable() if (waitingForFill) { - waitingForFill = _lock.runLocked(() -> _flushState == FlushState.WAIT_FOR_FILL); + try (AutoLock l = _lock.lock()) + { + waitingForFill = _flushState == FlushState.WAIT_FOR_FILL; + } if (waitingForFill) fill(BufferUtil.EMPTY_BUFFER); } @@ -544,7 +547,7 @@ protected void onFillableFail(Throwable failure) { // If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read boolean fail = false; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("onFillableFail {}", SslConnection.this, failure); @@ -593,7 +596,7 @@ public int fill(ByteBuffer buffer) throws IOException { try { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug(">fill {}", SslConnection.this); @@ -813,7 +816,7 @@ protected void needsFillInterest() boolean fillable; ByteBuffer write = null; boolean interest = false; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug(">needFillInterest s={}/{} uf={} ei={} di={} {}", @@ -957,7 +960,7 @@ public boolean flush(ByteBuffer... appOuts) throws IOException { try { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (LOG.isDebugEnabled()) { @@ -1147,7 +1150,7 @@ protected void onIncompleteFlush() { boolean fillInterest = false; ByteBuffer write = null; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug(">onIncompleteFlush {} {}", SslConnection.this, BufferUtil.toDetailString(_encryptedOutput)); @@ -1241,7 +1244,7 @@ public void doShutdownOutput() { boolean close; boolean flush = false; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { boolean ishut = endPoint.isInputShutdown(); boolean oshut = endPoint.isOutputShutdown(); @@ -1267,7 +1270,7 @@ public void doShutdownOutput() // If we still can't flush, but we are not closing the endpoint, // let's just flush the encrypted output in the background. ByteBuffer write = null; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (BufferUtil.hasContent(_encryptedOutput)) { @@ -1279,7 +1282,7 @@ public void doShutdownOutput() { endPoint.write(Callback.from(() -> { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _flushState = FlushState.IDLE; releaseEncryptedOutputBuffer(); @@ -1454,7 +1457,7 @@ private boolean isTLS13() private Throwable handleException(Throwable x, String context) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_failure == null) { @@ -1496,7 +1499,7 @@ public void succeeded() { boolean fillable; boolean interested; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("IncompleteWriteCB succeeded {}", SslConnection.this); @@ -1521,7 +1524,7 @@ else if (fillable) public void failed(final Throwable x) { boolean failFillInterest; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("IncompleteWriteCB failed {}", SslConnection.this, x); diff --git a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java index 3568b735a7a1..6b2a9a64e430 100644 --- a/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java +++ b/jetty-jaas/src/main/java/org/eclipse/jetty/jaas/spi/UserInfo.java @@ -36,9 +36,9 @@ public class UserInfo { private final AutoLock _lock = new AutoLock(); - protected final List _roleNames = new ArrayList<>(); - private final String _userName; - private final Credential _credential; + private String _userName; + private Credential _credential; + protected List _roleNames = new ArrayList<>(); protected boolean _rolesLoaded = false; /** @@ -81,7 +81,7 @@ public List doFetchRoles() public void fetchRoles() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (!_rolesLoaded) { diff --git a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java index 6460b9646366..62edd1d6237e 100644 --- a/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java +++ b/jetty-jndi/src/main/java/org/eclipse/jetty/jndi/ContextFactory.java @@ -41,12 +41,12 @@ * This is an object factory that produces a jndi naming * context based on a classloader. *

- * It is used for the {@code java:comp} context. + * It is used for the java:comp context. *

- * This object factory is bound at {@code java:comp}. When a + * This object factory is bound at java:comp. When a * lookup arrives for java:comp, this object factory * is invoked and will return a context specific to - * the caller's environment (so producing the {@code java:comp/env} + * the caller's environment (so producing the java:comp/env * specific to a webapp). *

* The context selected is based on classloaders. First @@ -69,13 +69,13 @@ public class ContextFactory implements ObjectFactory * Threadlocal for injecting a context to use * instead of looking up the map. */ - private static final ThreadLocal __threadContext = new ThreadLocal<>(); + private static final ThreadLocal __threadContext = new ThreadLocal(); /** * Threadlocal for setting a classloader which must be used * when finding the comp context. */ - private static final ThreadLocal __threadClassLoader = new ThreadLocal<>(); + private static final ThreadLocal __threadClassLoader = new ThreadLocal(); private static final AutoLock __lock = new AutoLock(); @@ -92,6 +92,8 @@ public class ContextFactory implements ObjectFactory *

* If there is no current jetty Context, or it has no associated classloader, we * return null. + * + * @see javax.naming.spi.ObjectFactory#getObjectInstance(java.lang.Object, javax.naming.Name, javax.naming.Context, java.util.Hashtable) */ @Override public Object getObjectInstance(Object obj, @@ -101,7 +103,7 @@ public Object getObjectInstance(Object obj, throws Exception { //First, see if we have had a context injected into us to use. - Context ctx = __threadContext.get(); + Context ctx = (Context)__threadContext.get(); if (ctx != null) { if (LOG.isDebugEnabled()) @@ -111,12 +113,12 @@ public Object getObjectInstance(Object obj, //See if there is a classloader to use for finding the comp context //Don't use its parent hierarchy if set. - ClassLoader loader = __threadClassLoader.get(); + ClassLoader loader = (ClassLoader)__threadClassLoader.get(); if (loader != null) { if (LOG.isDebugEnabled()) LOG.debug("Using threadlocal classloader"); - try (AutoLock ignored = __lock.lock()) + try (AutoLock l = __lock.lock()) { ctx = getContextForClassLoader(loader); if (ctx == null) @@ -137,12 +139,12 @@ public Object getObjectInstance(Object obj, { if (LOG.isDebugEnabled()) LOG.debug("Trying thread context classloader"); - try (AutoLock ignored = __lock.lock()) + try (AutoLock l = __lock.lock()) { while (ctx == null && loader != null) { ctx = getContextForClassLoader(loader); - if (ctx == null) + if (ctx == null && loader != null) loader = loader.getParent(); } @@ -161,12 +163,12 @@ public Object getObjectInstance(Object obj, //classloader associated with the current context if (ContextHandler.getCurrentContext() != null) { - if (LOG.isDebugEnabled()) + if (LOG.isDebugEnabled() && loader != null) LOG.debug("Trying classloader of current org.eclipse.jetty.server.handler.ContextHandler"); - try (AutoLock ignored = __lock.lock()) + try (AutoLock l = __lock.lock()) { loader = ContextHandler.getCurrentContext().getContextHandler().getClassLoader(); - ctx = __contextMap.get(loader); + ctx = (Context)__contextMap.get(loader); if (ctx == null && loader != null) { @@ -220,8 +222,10 @@ public Context getContextForClassLoader(ClassLoader loader) { if (loader == null) return null; - - return __lock.runLocked(() -> __contextMap.get(loader)); + try (AutoLock l = __lock.lock()) + { + return __contextMap.get(loader); + } } /** @@ -233,7 +237,7 @@ public Context getContextForClassLoader(ClassLoader loader) */ public static Context associateContext(final Context ctx) { - Context previous = __threadContext.get(); + Context previous = (Context)__threadContext.get(); __threadContext.set(ctx); return previous; } @@ -245,7 +249,7 @@ public static void disassociateContext(final Context ctx) public static ClassLoader associateClassLoader(final ClassLoader loader) { - ClassLoader prev = __threadClassLoader.get(); + ClassLoader prev = (ClassLoader)__threadClassLoader.get(); __threadClassLoader.set(loader); return prev; } @@ -257,7 +261,7 @@ public static void disassociateClassLoader() public static void dump(Appendable out, String indent) throws IOException { - try (AutoLock ignored = __lock.lock()) + try (AutoLock l = __lock.lock()) { Dumpable.dumpObjects(out, indent, String.format("o.e.j.jndi.ContextFactory@%x", __contextMap.hashCode()), __contextMap); } diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java index 9c0aa2ca2d74..53020d8bc916 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/DigestAuthenticator.java @@ -297,7 +297,7 @@ public Nonce(String nonce, long ts, int size) public boolean seen(int count) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (count >= _seen.size()) return true; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java index f45210e989ab..d883045f2b16 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java @@ -33,6 +33,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; +import java.util.concurrent.locks.Condition; import java.util.stream.Collectors; import org.eclipse.jetty.io.ArrayByteBufferPool; @@ -142,7 +143,8 @@ public abstract class AbstractConnector extends ContainerLifeCycle implements Co { protected static final Logger LOG = LoggerFactory.getLogger(AbstractConnector.class); - private final AutoLock.WithCondition _lock = new AutoLock.WithCondition(); + private final AutoLock _lock = new AutoLock(); + private final Condition _setAccepting = _lock.newCondition(); private final Map _factories = new LinkedHashMap<>(); // Order is important on server side, so we use a LinkedHashMap private final Server _server; private final Executor _executor; @@ -446,10 +448,10 @@ public boolean isAccepting() public void setAccepting(boolean accepting) { - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { _accepting = accepting; - lock.signalAll(); + _setAccepting.signalAll(); } } @@ -702,17 +704,20 @@ public void run() if (_acceptorPriorityDelta != 0) thread.setPriority(Math.max(Thread.MIN_PRIORITY, Math.min(Thread.MAX_PRIORITY, priority + _acceptorPriorityDelta))); - _lock.runLocked(() -> _acceptors[_id] = thread); + try (AutoLock l = _lock.lock()) + { + _acceptors[_id] = thread; + } try { while (isRunning() && !_shutdown.isShutdown()) { - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (!_accepting && isRunning()) { - lock.await(); + _setAccepting.await(); continue; } } @@ -738,8 +743,10 @@ public void run() if (_acceptorPriorityDelta != 0) thread.setPriority(priority); - _lock.runLocked(() -> _acceptors[_id] = null); - + try (AutoLock l = _lock.lock()) + { + _acceptors[_id] = null; + } Shutdown shutdown = _shutdown; if (shutdown != null) shutdown.check(); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AcceptRateLimit.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AcceptRateLimit.java index c8e69d34db04..d69c653a26d0 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/AcceptRateLimit.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AcceptRateLimit.java @@ -125,7 +125,7 @@ public long getMaxRate() @ManagedOperation(value = "Resets the accept rate", impact = "ACTION") public void reset() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _rate.reset(); if (_limiting) @@ -144,7 +144,7 @@ protected void age(long period, TimeUnit units) @Override protected void doStart() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_server != null) { @@ -170,7 +170,7 @@ protected void doStart() throws Exception @Override protected void doStop() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_task != null) _task.cancel(); @@ -205,7 +205,7 @@ protected void unlimit() @Override public void onAccepting(SelectableChannel channel) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { int rate = _rate.record(); if (LOG.isDebugEnabled()) @@ -215,6 +215,7 @@ public void onAccepting(SelectableChannel channel) if (!_limiting) { _limiting = true; + LOG.warn("AcceptLimit rate exceeded {}>{} on {}", rate, _acceptRateLimit, _connectors); limit(); } @@ -237,7 +238,7 @@ private void schedule() @Override public void run() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _task = null; if (!isRunning()) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java index 1136330806be..bdedf66c7eb7 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ConnectionLimit.java @@ -64,9 +64,9 @@ public class ConnectionLimit extends AbstractLifeCycle implements Listener, Sele private static final Logger LOG = LoggerFactory.getLogger(ConnectionLimit.class); private final AutoLock _lock = new AutoLock(); + private final Server _server; private final List _connectors = new ArrayList<>(); private final Set _accepting = new HashSet<>(); - private final Server _server; private int _connections; private int _maxConnections; private long _idleTimeout; @@ -110,24 +110,33 @@ public void setIdleTimeout(long idleTimeout) @ManagedAttribute("The maximum number of connections allowed") public int getMaxConnections() { - return _lock.runLocked(() -> _maxConnections); + try (AutoLock l = _lock.lock()) + { + return _maxConnections; + } } public void setMaxConnections(int max) { - _lock.runLocked(() -> _maxConnections = max); + try (AutoLock l = _lock.lock()) + { + _maxConnections = max; + } } @ManagedAttribute("The current number of connections ") public int getConnections() { - return _lock.runLocked(() -> _connections); + try (AutoLock l = _lock.lock()) + { + return _connections; + } } @Override protected void doStart() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_server != null) { @@ -153,7 +162,7 @@ protected void doStart() throws Exception @Override protected void doStop() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { for (AbstractConnector c : _connectors) { @@ -222,7 +231,7 @@ protected void unlimit() @Override public void onAccepting(SelectableChannel channel) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _accepting.add(channel); if (LOG.isDebugEnabled()) @@ -234,7 +243,7 @@ public void onAccepting(SelectableChannel channel) @Override public void onAcceptFailed(SelectableChannel channel, Throwable cause) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _accepting.remove(channel); if (LOG.isDebugEnabled()) @@ -251,7 +260,7 @@ public void onAccepted(SelectableChannel channel) @Override public void onOpened(Connection connection) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _accepting.remove(connection.getEndPoint().getTransport()); _connections++; @@ -264,7 +273,7 @@ public void onOpened(Connection connection) @Override public void onClosed(Connection connection) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _connections--; if (LOG.isDebugEnabled()) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java index 7fd6830b42fd..a2190b2689a6 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpChannelState.java @@ -21,7 +21,6 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; import javax.servlet.AsyncListener; import javax.servlet.ServletContext; import javax.servlet.ServletResponse; @@ -169,19 +168,17 @@ AutoLock lock() return _lock.lock(); } - R runLocked(Supplier code) - { - return _lock.runLocked(code); - } - public State getState() { - return runLocked(() -> _state); + try (AutoLock l = lock()) + { + return _state; + } } public void addListener(AsyncListener listener) { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_asyncListeners == null) _asyncListeners = new ArrayList<>(); @@ -210,28 +207,43 @@ public boolean hasListener(AsyncListener listener) public boolean isSendError() { - return runLocked(() -> _sendError); + try (AutoLock l = lock()) + { + return _sendError; + } } public void setTimeout(long ms) { - runLocked(() -> _timeoutMs = ms); + try (AutoLock l = lock()) + { + _timeoutMs = ms; + } } public long getTimeout() { - return runLocked(() -> _timeoutMs); + try (AutoLock l = lock()) + { + return _timeoutMs; + } } public AsyncContextEvent getAsyncContextEvent() { - return runLocked(() -> _event); + try (AutoLock l = lock()) + { + return _event; + } } @Override public String toString() { - return runLocked(this::toStringLocked); + try (AutoLock l = lock()) + { + return toStringLocked(); + } } private String toStringLocked() @@ -257,12 +269,15 @@ private String getStatusStringLocked() public String getStatusString() { - return runLocked(this::getStatusStringLocked); + try (AutoLock l = lock()) + { + return getStatusStringLocked(); + } } public boolean commitResponse() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { switch (_outputState) { @@ -278,7 +293,7 @@ public boolean commitResponse() public boolean partialResponse() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { switch (_outputState) { @@ -294,7 +309,7 @@ public boolean partialResponse() public boolean completeResponse() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { switch (_outputState) { @@ -311,7 +326,7 @@ public boolean completeResponse() public boolean isResponseCommitted() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = lock()) { switch (_outputState) { @@ -325,12 +340,15 @@ public boolean isResponseCommitted() public boolean isResponseCompleted() { - return runLocked(() -> _outputState == OutputState.COMPLETED); + try (AutoLock l = lock()) + { + return _outputState == OutputState.COMPLETED; + } } public boolean abortResponse() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { switch (_outputState) { @@ -354,7 +372,7 @@ public boolean abortResponse() */ public Action handling() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("handling {}", toStringLocked()); @@ -396,7 +414,7 @@ public Action handling() */ protected Action unhandle() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("unhandle {}", toStringLocked()); @@ -515,7 +533,7 @@ public void startAsync(AsyncContextEvent event) { final List lastAsyncListeners; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("startAsync {}", toStringLocked()); @@ -564,7 +582,7 @@ public void dispatch(ServletContext context, String path) { boolean dispatch = false; AsyncContextEvent event; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("dispatch {} -> {}", toStringLocked(), path); @@ -600,7 +618,7 @@ public void dispatch(ServletContext context, String path) protected void timeout() { boolean dispatch = false; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("Timeout {}", toStringLocked()); @@ -628,7 +646,7 @@ protected void onTimeout() { final List listeners; AsyncContextEvent event; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onTimeout {}", toStringLocked()); @@ -676,7 +694,7 @@ public void complete() { boolean handle = false; AsyncContextEvent event; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("complete {}", toStringLocked()); @@ -714,7 +732,7 @@ public void asyncError(Throwable failure) // actually handled by #thrownException AsyncContextEvent event = null; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("asyncError " + toStringLocked(), failure); @@ -745,7 +763,7 @@ protected void onError(Throwable th) { final AsyncContextEvent asyncEvent; final List asyncListeners; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("thrownException " + getStatusStringLocked(), th); @@ -809,7 +827,7 @@ protected void onError(Throwable th) }); // check the actions of the listeners - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_requestState == RequestState.ASYNC && !_sendError) { @@ -881,7 +899,7 @@ public void sendError(int code, String message) if (message == null) message = HttpStatus.getMessage(code); - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("sendError {}", toStringLocked()); @@ -922,7 +940,7 @@ public void sendError(int code, String message) protected void completing() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("completing {}", toStringLocked()); @@ -943,7 +961,7 @@ protected void completed(Throwable failure) final AsyncContextEvent event; boolean handle = false; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("completed {}", toStringLocked()); @@ -997,7 +1015,7 @@ protected void completed(Throwable failure) } event.completed(); - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { _requestState = RequestState.COMPLETED; if (_state == State.WAITING) @@ -1015,7 +1033,7 @@ protected void completed(Throwable failure) protected void recycle() { cancelTimeout(); - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("recycle {}", toStringLocked()); @@ -1044,7 +1062,7 @@ protected void recycle() public void upgrade() { cancelTimeout(); - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("upgrade {}", toStringLocked()); @@ -1074,8 +1092,7 @@ protected void scheduleDispatch() protected void cancelTimeout() { - AsyncContextEvent event = runLocked(() -> _event); - cancelTimeout(event); + cancelTimeout(getAsyncContextEvent()); } protected void cancelTimeout(AsyncContextEvent event) @@ -1086,33 +1103,48 @@ protected void cancelTimeout(AsyncContextEvent event) public boolean isIdle() { - return runLocked(() -> _state == State.IDLE); + try (AutoLock l = lock()) + { + return _state == State.IDLE; + } } public boolean isExpired() { - // TODO review - return runLocked(() -> _requestState == RequestState.EXPIRE || _requestState == RequestState.EXPIRING); + try (AutoLock l = lock()) + { + // TODO review + return _requestState == RequestState.EXPIRE || _requestState == RequestState.EXPIRING; + } } public boolean isInitial() { - return runLocked(() -> _initial); + try (AutoLock l = lock()) + { + return _initial; + } } public boolean isSuspended() { - return runLocked(() -> _state == State.WAITING || _state == State.HANDLING && _requestState == RequestState.ASYNC); + try (AutoLock l = lock()) + { + return _state == State.WAITING || _state == State.HANDLING && _requestState == RequestState.ASYNC; + } } boolean isCompleted() { - return runLocked(() -> _requestState == RequestState.COMPLETED); + try (AutoLock l = lock()) + { + return _requestState == RequestState.COMPLETED; + } } public boolean isAsyncStarted() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_state == State.HANDLING) return _requestState != RequestState.BLOCKING; @@ -1122,7 +1154,10 @@ public boolean isAsyncStarted() public boolean isAsync() { - return runLocked(() -> !_initial || _requestState != RequestState.BLOCKING); + try (AutoLock l = lock()) + { + return !_initial || _requestState != RequestState.BLOCKING; + } } public Request getBaseRequest() @@ -1197,7 +1232,7 @@ public void setAttribute(String name, Object attribute) public void onReadUnready() { boolean interested = false; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onReadUnready {}", toStringLocked()); @@ -1243,7 +1278,7 @@ public void onReadUnready() public boolean onContentAdded() { boolean woken = false; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onContentAdded {}", toStringLocked()); @@ -1286,7 +1321,7 @@ public boolean onContentAdded() public boolean onReadReady() { boolean woken = false; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onReadReady {}", toStringLocked()); @@ -1319,7 +1354,7 @@ public boolean onReadReady() public boolean onReadPossible() { boolean woken = false; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onReadPossible {}", toStringLocked()); @@ -1351,7 +1386,7 @@ public boolean onReadPossible() public boolean onReadEof() { boolean woken = false; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onEof {}", toStringLocked()); @@ -1371,7 +1406,7 @@ public boolean onWritePossible() { boolean wake = false; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (LOG.isDebugEnabled()) LOG.debug("onWritePossible {}", toStringLocked()); diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpInput.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpInput.java index 34d7e6302995..074fa9c7768c 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpInput.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpInput.java @@ -153,7 +153,7 @@ protected HttpChannelState getHttpChannelState() public void recycle() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_content != null) _content.failed(null); @@ -214,7 +214,7 @@ public int available() { int available = 0; boolean woken = false; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_content == null) _content = _inputQ.poll(); @@ -261,8 +261,8 @@ public int read() throws IOException public int read(byte[] b, int off, int len) throws IOException { boolean wake = false; - int l; - try (AutoLock ignored = _lock.lock()) + int read; + try (AutoLock l = _lock.lock()) { // Calculate minimum request rate for DOS protection long minRequestDataRate = _channelState.getHttpChannel().getHttpConfiguration().getMinRequestDataRate(); @@ -289,9 +289,9 @@ public int read(byte[] b, int off, int len) throws IOException Content item = nextContent(); if (item != null) { - l = get(item, b, off, len); + read = get(item, b, off, len); if (LOG.isDebugEnabled()) - LOG.debug("{} read {} from {}", this, l, item); + LOG.debug("{} read {} from {}", this, read, item); // Consume any following poison pills if (item.isEmpty()) @@ -303,9 +303,9 @@ public int read(byte[] b, int off, int len) throws IOException if (!_state.blockForContent(this)) { // Not blocking, so what should we return? - l = _state.noContent(); + read = _state.noContent(); - if (l < 0) + if (read < 0) // If EOF do we need to wake for allDataRead callback? wake = _channelState.onReadEof(); break; @@ -315,7 +315,7 @@ public int read(byte[] b, int off, int len) throws IOException if (wake) wake(); - return l; + return read; } /** @@ -335,7 +335,7 @@ protected void produceContent() throws IOException */ public void asyncReadProduce() throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { produceContent(); } @@ -524,6 +524,7 @@ protected void skip(Content content, int length) */ protected void blockForContent() throws IOException { + assert _lock.isHeldByCurrentThread(); try { _waitingForContent = true; @@ -562,7 +563,7 @@ protected void blockForContent() throws IOException */ public boolean addContent(Content content) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _waitingForContent = false; if (_firstByteTimeStamp == -1) @@ -596,20 +597,26 @@ public boolean addContent(Content content) public boolean hasContent() { - return _lock.runLocked(() -> _content != null || _inputQ.size() > 0); + try (AutoLock l = _lock.lock()) + { + return _content != null || _inputQ.size() > 0; + } } public void unblock() { - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock.WithCondition l = _lock.lock()) { - lock.signal(); + l.signal(); } } public long getContentConsumed() { - return _lock.runLocked(() -> _contentConsumed); + try (AutoLock l = _lock.lock()) + { + return _contentConsumed; + } } /** @@ -636,7 +643,7 @@ public boolean eof() public boolean consumeAll() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { try { @@ -665,18 +672,27 @@ public boolean consumeAll() public boolean isError() { - return _lock.runLocked(() -> _state instanceof ErrorState); + try (AutoLock l = _lock.lock()) + { + return _state instanceof ErrorState; + } } public boolean isAsync() { - return _lock.runLocked(() -> _state == ASYNC); + try (AutoLock l = _lock.lock()) + { + return _state == ASYNC; + } } @Override public boolean isFinished() { - return _lock.runLocked(() -> _state instanceof EOFState); + try (AutoLock l = _lock.lock()) + { + return _state instanceof EOFState; + } } @Override @@ -684,7 +700,7 @@ public boolean isReady() { try { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_listener == null) return true; @@ -712,7 +728,7 @@ public void setReadListener(ReadListener readListener) boolean woken = false; try { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_listener != null) throw new IllegalStateException("ReadListener already set"); @@ -760,7 +776,7 @@ else if (_state == EOF) public boolean onIdleTimeout(Throwable x) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { boolean neverDispatched = getHttpChannelState().isIdle(); if ((_waitingForContent || neverDispatched) && !isError()) @@ -775,7 +791,7 @@ public boolean onIdleTimeout(Throwable x) public boolean failed(Throwable x) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // Errors may be reported multiple times, for example // a local idle timeout and a remote I/O failure. @@ -803,6 +819,7 @@ public boolean failed(Throwable x) private boolean wakeup() { + assert _lock.isHeldByCurrentThread(); if (_listener != null) return _channelState.onContentAdded(); _lock.signal(); @@ -820,7 +837,7 @@ public void run() Throwable error; boolean aeof = false; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { listener = _listener; @@ -909,7 +926,7 @@ public String toString() long consumed; int q; Content content; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { state = _state; consumed = _contentConsumed; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpOutput.java b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpOutput.java index 70c3c5f5a73f..834938e57f11 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/HttpOutput.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/HttpOutput.java @@ -239,7 +239,10 @@ public long getWritten() public void reopen() { - _channelState.runLocked(() -> _softClose = false); + try (AutoLock l = _channelState.lock()) + { + _softClose = false; + } } protected Blocker acquireWriteBlockingCallback() throws IOException @@ -276,7 +279,7 @@ private void onWriteComplete(boolean last, Throwable failure) boolean wake = false; Callback closedCallback = null; ByteBuffer closeContent = null; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { if (LOG.isDebugEnabled()) state = stateString(); @@ -379,7 +382,10 @@ private int maximizeAggregateSpace() public void softClose() { - _channelState.runLocked(() -> _softClose = true); + try (AutoLock l = _channelState.lock()) + { + _softClose = true; + } } public void complete(Callback callback) @@ -392,7 +398,7 @@ public void complete(Callback callback) boolean succeeded = false; Throwable error = null; ByteBuffer content = null; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { switch (_state) { @@ -468,7 +474,7 @@ public void complete(Callback callback) */ public void completed(Throwable failure) { - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { _state = State.CLOSED; releaseBuffer(failure); @@ -480,7 +486,7 @@ public void close() throws IOException { ByteBuffer content = null; Blocker blocker = null; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { if (_onError != null) { @@ -597,7 +603,10 @@ public void close() throws IOException public ByteBuffer getBuffer() { - return _channelState.runLocked(this::acquireBuffer); + try (AutoLock l = _channelState.lock()) + { + return acquireBuffer(); + } } private ByteBuffer acquireBuffer() @@ -622,12 +631,15 @@ private void releaseBuffer(Throwable failure) public boolean isClosed() { - return _channelState.runLocked(() -> _softClose || (_state != State.OPEN)); + try (AutoLock l = _channelState.lock()) + { + return _softClose || (_state != State.OPEN); + } } public boolean isAsync() { - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { switch (_apiState) { @@ -646,7 +658,7 @@ public boolean isAsync() public void flush() throws IOException { ByteBuffer content = null; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { switch (_state) { @@ -729,7 +741,7 @@ public void write(byte[] b, int off, int len) throws IOException // Async or Blocking ? boolean async; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { checkWritable(); long written = _written + len; @@ -860,7 +872,7 @@ public void write(ByteBuffer buffer) throws IOException // Async or Blocking ? boolean async; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { checkWritable(); long written = _written + len; @@ -935,7 +947,7 @@ public void write(int b) throws IOException // Async or Blocking ? boolean async = false; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { checkWritable(); long written = _written + 1; @@ -1198,7 +1210,7 @@ public void sendContent(ReadableByteChannel in, Callback callback) private boolean prepareSendContent(int len, Callback callback) { - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { if (BufferUtil.hasContent(_aggregate)) { @@ -1336,7 +1348,7 @@ public void onFlushed(long bytes) throws IOException public void recycle() { - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { _state = State.OPEN; _apiState = ApiState.BLOCKING; @@ -1359,7 +1371,7 @@ public void recycle() public void resetBuffer() { - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { _interceptor.resetBuffer(); if (BufferUtil.hasContent(_aggregate)) @@ -1374,7 +1386,7 @@ public void setWriteListener(WriteListener writeListener) if (!_channel.getState().isAsync()) throw new IllegalStateException("!ASYNC: " + stateString()); boolean wake; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { if (_apiState != ApiState.BLOCKING) throw new IllegalStateException("!OPEN" + stateString()); @@ -1389,7 +1401,7 @@ public void setWriteListener(WriteListener writeListener) @Override public boolean isReady() { - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { switch (_apiState) { @@ -1420,7 +1432,7 @@ public void run() { Throwable error = null; - try (AutoLock ignored = _channelState.lock()) + try (AutoLock l = _channelState.lock()) { if (_onError != null) { @@ -1471,7 +1483,10 @@ private String stateString() @Override public String toString() { - return _channelState.runLocked(() -> String.format("%s@%x{%s}", this.getClass().getSimpleName(), hashCode(), stateString())); + try (AutoLock l = _channelState.lock()) + { + return String.format("%s@%x{%s}", this.getClass().getSimpleName(), hashCode(), stateString()); + } } private abstract class ChannelWriteCB extends IteratingCallback diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java b/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java index 91101c544f66..5af0c8913fc7 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/MultiPartFormInputStream.java @@ -103,7 +103,7 @@ private enum State private volatile boolean _deleteOnExit; private volatile boolean _writeFilesWithFilenames; private volatile int _bufferSize = 16 * 1024; - private State _state = State.UNPARSED; + private State state = State.UNPARSED; public class MultiPart implements Part { @@ -378,7 +378,7 @@ public MultiPartFormInputStream(InputStream in, String contentType, MultipartCon if (((ServletInputStream)in).isFinished()) { _in = null; - _state = State.PARSED; + state = State.PARSED; return; } } @@ -410,24 +410,24 @@ public boolean isEmpty() */ public void deleteParts() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { - switch (_state) + switch (state) { case DELETED: case DELETING: return; case PARSING: - _state = State.DELETING; + state = State.DELETING; return; case UNPARSED: - _state = State.DELETED; + state = State.DELETED; return; case PARSED: - _state = State.DELETED; + state = State.DELETED; break; } } @@ -513,19 +513,19 @@ protected void throwIfError() throws IOException */ protected void parse() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { - switch (_state) + switch (state) { case UNPARSED: - _state = State.PARSING; + state = State.PARSING; break; case PARSED: return; default: - _err = new IOException(_state.name()); + _err = new IOException(state.name()); return; } } @@ -566,11 +566,11 @@ else if ("".equals(_config.getLocation())) while (true) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { - if (_state != State.PARSING) + if (state != State.PARSING) { - _err = new IOException(_state.name()); + _err = new IOException(state.name()); return; } } @@ -632,21 +632,21 @@ else if (len == -1) finally { boolean cleanup = false; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { - switch (_state) + switch (state) { case PARSING: - _state = State.PARSED; + state = State.PARSED; break; case DELETING: - _state = State.DELETED; + state = State.DELETED; cleanup = true; break; default: - _err = new IllegalStateException(_state.name()); + _err = new IllegalStateException(state.name()); } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/RequestLogWriter.java b/jetty-server/src/main/java/org/eclipse/jetty/server/RequestLogWriter.java index 2773ffdbe674..71986a36ba37 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/RequestLogWriter.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/RequestLogWriter.java @@ -177,7 +177,7 @@ public String getFilenameDateFormat() @Override public void write(String requestEntry) throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_writer == null) return; @@ -190,7 +190,7 @@ public void write(String requestEntry) throws IOException @Override protected void doStart() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_filename != null) { @@ -204,8 +204,8 @@ protected void doStart() throws Exception } _out = _fileOut; _writer = new OutputStreamWriter(_out); + super.doStart(); } - super.doStart(); } public void setTimeZone(String timeZone) @@ -222,9 +222,9 @@ public String getTimeZone() @Override protected void doStop() throws Exception { - super.doStop(); try (AutoLock ignored = _lock.lock()) { + super.doStop(); try { if (_writer != null) diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceService.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceService.java index 3be87aa28cbb..f5b9addebcce 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceService.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ResourceService.java @@ -377,19 +377,22 @@ protected void sendWelcome(HttpContent content, String pathInContext, boolean en if (!endsWithSlash) { StringBuffer buf = request.getRequestURL(); - int param = buf.lastIndexOf(";"); - if (param < 0) - buf.append('/'); - else - buf.insert(param, '/'); - String q = request.getQueryString(); - if (q != null && q.length() != 0) + synchronized (buf) { - buf.append('?'); - buf.append(q); + int param = buf.lastIndexOf(";"); + if (param < 0) + buf.append('/'); + else + buf.insert(param, '/'); + String q = request.getQueryString(); + if (q != null && q.length() != 0) + { + buf.append('?'); + buf.append(q); + } + response.setContentLength(0); + response.sendRedirect(response.encodeRedirectURL(buf.toString())); } - response.setContentLength(0); - response.sendRedirect(response.encodeRedirectURL(buf.toString())); return; } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/ShutdownMonitor.java b/jetty-server/src/main/java/org/eclipse/jetty/server/ShutdownMonitor.java index 8d32b47ee700..7f5851fe70cc 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/ShutdownMonitor.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/ShutdownMonitor.java @@ -98,9 +98,8 @@ public static boolean isRegistered(LifeCycle lifeCycle) /** * Creates a ShutdownMonitor using configuration from the System properties. *

- * {@code STOP.PORT} = the port to listen on (empty, null, or values less than 0 disable the stop ability) - *
- * {@code STOP.KEY} = the magic key/passphrase to allow the stop
+ * STOP.PORT = the port to listen on (empty, null, or values less than 0 disable the stop ability)
+ * STOP.KEY = the magic key/passphrase to allow the stop
*

* Note: server socket will only listen on localhost, and a successful stop will issue a System.exit() call. */ @@ -115,17 +114,26 @@ private ShutdownMonitor() private void addLifeCycles(LifeCycle... lifeCycles) { - _lock.runLocked(() -> _lifeCycles.addAll(Arrays.asList(lifeCycles))); + try (AutoLock l = _lock.lock()) + { + _lifeCycles.addAll(Arrays.asList(lifeCycles)); + } } private void removeLifeCycle(LifeCycle lifeCycle) { - _lock.runLocked(() -> _lifeCycles.remove(lifeCycle)); + try (AutoLock l = _lock.lock()) + { + _lifeCycles.remove(lifeCycle); + } } private boolean containsLifeCycle(LifeCycle lifeCycle) { - return _lock.runLocked(() -> _lifeCycles.contains(lifeCycle)); + try (AutoLock l = _lock.lock()) + { + return _lifeCycles.contains(lifeCycle); + } } private void debug(String format, Object... args) @@ -142,17 +150,26 @@ private void debug(Throwable t) public String getKey() { - return _lock.runLocked(() -> key); + try (AutoLock l = _lock.lock()) + { + return key; + } } public int getPort() { - return _lock.runLocked(() -> port); + try (AutoLock l = _lock.lock()) + { + return port; + } } public boolean isExitVm() { - return _lock.runLocked(() -> exitVm); + try (AutoLock l = _lock.lock()) + { + return exitVm; + } } public void setDebug(boolean flag) @@ -165,7 +182,7 @@ public void setDebug(boolean flag) */ public void setExitVm(boolean exitVm) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (alive) throw new IllegalStateException("ShutdownMonitor already started"); @@ -175,7 +192,7 @@ public void setExitVm(boolean exitVm) public void setKey(String key) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (alive) throw new IllegalStateException("ShutdownMonitor already started"); @@ -185,7 +202,7 @@ public void setKey(String key) public void setPort(int port) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (alive) throw new IllegalStateException("ShutdownMonitor already started"); @@ -195,7 +212,7 @@ public void setPort(int port) protected void start() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (alive) { @@ -216,28 +233,31 @@ protected void start() throws Exception private void stop() { - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock.WithCondition l = _lock.lock()) { alive = false; - lock.signalAll(); + l.signalAll(); } } // For test purposes only. void await() throws InterruptedException { - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock.WithCondition l = _lock.lock()) { while (alive) { - lock.await(); + l.await(); } } } protected boolean isAlive() { - return _lock.runLocked(() -> alive); + try (AutoLock l = _lock.lock()) + { + return alive; + } } private ServerSocket listen() @@ -411,7 +431,12 @@ private void informClient(OutputStream out, String message) throws IOException private void stopLifeCycles(Predicate predicate, boolean destroy) { - List lifeCycles = _lock.runLocked(() -> new ArrayList<>(_lifeCycles)); + List lifeCycles; + try (AutoLock l = _lock.lock()) + { + lifeCycles = new ArrayList<>(_lifeCycles); + } + for (LifeCycle l : lifeCycles) { try diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java index 941bcacbee08..72b77cd68af5 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java @@ -129,12 +129,19 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu }; public static final int DEFAULT_LISTENER_TYPE_INDEX = 1; + public static final int EXTENDED_LISTENER_TYPE_INDEX = 0; + private static final String UNIMPLEMENTED_USE_SERVLET_CONTEXT_HANDLER = "Unimplemented {} - use org.eclipse.jetty.servlet.ServletContextHandler"; + private static final Logger LOG = LoggerFactory.getLogger(ContextHandler.class); + private static final ThreadLocal __context = new ThreadLocal<>(); + private static String __serverInfo = "jetty/" + Server.getVersion(); + public static final String MANAGED_ATTRIBUTES = "org.eclipse.jetty.server.context.ManagedAttributes"; + public static final String MAX_FORM_KEYS_KEY = "org.eclipse.jetty.server.Request.maxFormKeys"; public static final String MAX_FORM_CONTENT_SIZE_KEY = "org.eclipse.jetty.server.Request.maxFormContentSize"; public static final int DEFAULT_MAX_FORM_KEYS = 1000; @@ -204,6 +211,7 @@ public enum ContextStatus private int _maxFormContentSize = Integer.getInteger(MAX_FORM_CONTENT_SIZE_KEY, DEFAULT_MAX_FORM_CONTENT_SIZE); private boolean _compactPath = false; private boolean _usingSecurityManager = System.getSecurityManager() != null; + private final List _programmaticListeners = new CopyOnWriteArrayList<>(); private final List _servletContextListeners = new CopyOnWriteArrayList<>(); private final List _destroyServletContextListeners = new ArrayList<>(); @@ -214,13 +222,15 @@ public enum ContextStatus private final Set _durableListeners = new HashSet<>(); private String[] _protectedTargets; private final CopyOnWriteArrayList _aliasChecks = new CopyOnWriteArrayList<>(); - private Availability _availability = Availability.UNAVAILABLE; public enum Availability { UNAVAILABLE, STARTING, AVAILABLE, SHUTDOWN, } + ; + private volatile Availability _availability = Availability.UNAVAILABLE; + public ContextHandler() { this(null, null, null); @@ -513,7 +523,7 @@ public Attributes getAttributes() */ public ClassLoader getClassLoader() { - return _lock.runLocked(() -> _classLoader); + return _classLoader; } /** @@ -524,10 +534,9 @@ public ClassLoader getClassLoader() @ManagedAttribute("The file classpath") public String getClassPath() { - ClassLoader classLoader = getClassLoader(); - if (!(classLoader instanceof URLClassLoader)) + if (_classLoader == null || !(_classLoader instanceof URLClassLoader)) return null; - URLClassLoader loader = (URLClassLoader)classLoader; + URLClassLoader loader = (URLClassLoader)_classLoader; URL[] urls = loader.getURLs(); StringBuilder classpath = new StringBuilder(); for (int i = 0; i < urls.length; i++) @@ -739,7 +748,7 @@ public CompletableFuture shutdown() */ public boolean isAvailable() { - return _lock.runLocked(() -> _availability == Availability.AVAILABLE); + return _availability == Availability.AVAILABLE; } /** @@ -749,7 +758,7 @@ public boolean isAvailable() */ public void setAvailable(boolean available) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (available && isRunning()) _availability = Availability.AVAILABLE; @@ -790,15 +799,14 @@ protected void doStart() throws Exception _durableListeners.addAll(getEventListeners()); - ClassLoader classLoader = getClassLoader(); try { // Set the classloader, context and enter scope - if (classLoader != null) + if (_classLoader != null) { currentThread = Thread.currentThread(); oldClassloader = currentThread.getContextClassLoader(); - currentThread.setContextClassLoader(classLoader); + currentThread.setContextClassLoader(_classLoader); } oldContext = __context.get(); __context.set(_scontext); @@ -819,7 +827,7 @@ protected void doStart() throws Exception exitScope(null); __context.set(oldContext); // reset the classloader - if (classLoader != null && currentThread != null) + if (_classLoader != null && currentThread != null) currentThread.setContextClassLoader(oldClassloader); } } @@ -996,13 +1004,12 @@ protected void doStop() throws Exception try { // Set the classloader - ClassLoader classLoader = getClassLoader(); - if (classLoader != null) + if (_classLoader != null) { - oldWebapploader = classLoader; + oldWebapploader = _classLoader; currentThread = Thread.currentThread(); oldClassloader = currentThread.getContextClassLoader(); - currentThread.setContextClassLoader(classLoader); + currentThread.setContextClassLoader(_classLoader); } stopContext(); @@ -1202,9 +1209,8 @@ else if (_contextPath.length() == 1) } } - ClassLoader classLoader = getClassLoader(); - if (classLoader != null) - currentThread.setContextClassLoader(classLoader); + if (_classLoader != null) + currentThread.setContextClassLoader(_classLoader); try { @@ -1229,7 +1235,7 @@ else if (_contextPath.length() == 1) exitScope(baseRequest); // reset the classloader - if (classLoader != null) + if (_classLoader != null) currentThread.setContextClassLoader(oldClassloader); // reset the context and servlet path. @@ -1356,6 +1362,8 @@ protected void exitScope(Request request) */ public void handle(Request request, Runnable runnable) { + ClassLoader oldClassloader = null; + Thread currentThread = null; Context oldContext = __context.get(); // Are we already in the scope? @@ -1366,18 +1374,16 @@ public void handle(Request request, Runnable runnable) } // Nope, so enter the scope and then exit - ClassLoader classLoader = getClassLoader(); - ClassLoader oldClassLoader = null; try { __context.set(_scontext); // Set the classloader - if (classLoader != null) + if (_classLoader != null) { - Thread currentThread = Thread.currentThread(); - oldClassLoader = currentThread.getContextClassLoader(); - currentThread.setContextClassLoader(classLoader); + currentThread = Thread.currentThread(); + oldClassloader = currentThread.getContextClassLoader(); + currentThread.setContextClassLoader(_classLoader); } enterScope(request, runnable); @@ -1388,8 +1394,10 @@ public void handle(Request request, Runnable runnable) exitScope(request); __context.set(oldContext); - if (classLoader != null) - Thread.currentThread().setContextClassLoader(oldClassLoader); + if (oldClassloader != null) + { + currentThread.setContextClassLoader(oldClassloader); + } } } @@ -1496,7 +1504,7 @@ public void clearAttributes() */ public void setClassLoader(ClassLoader classLoader) { - _lock.runLocked(() -> _classLoader = classLoader); + _classLoader = classLoader; } /** @@ -1782,11 +1790,13 @@ public Class loadClass(String className) throws ClassNotFoundException if (className == null) return null; - ClassLoader classLoader = getClassLoader(); - if (classLoader == null) - return Loader.loadClass(className); + try (AutoLock l = _lock.lock()) + { + if (_classLoader == null) + return Loader.loadClass(className); - return classLoader.loadClass(className); + return _classLoader.loadClass(className); + } } public void addLocaleEncoding(String locale, String encoding) @@ -2258,7 +2268,7 @@ public Enumeration getInitParameterNames() @Override public Object getAttribute(String name) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { Object o = ContextHandler.this.getAttribute(name); if (o == null) @@ -2270,7 +2280,7 @@ public Object getAttribute(String name) @Override public Enumeration getAttributeNames() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { HashSet set = new HashSet<>(); Enumeration e = super.getAttributeNames(); @@ -2290,7 +2300,7 @@ public Enumeration getAttributeNames() @Override public void setAttribute(String name, Object value) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { Object oldValue = super.getAttribute(name); @@ -2302,14 +2312,15 @@ public void setAttribute(String name, Object value) if (!_servletContextAttributeListeners.isEmpty()) { ServletContextAttributeEvent event = new ServletContextAttributeEvent(_scontext, name, oldValue == null ? value : oldValue); - for (ServletContextAttributeListener l : _servletContextAttributeListeners) + + for (ServletContextAttributeListener listener : _servletContextAttributeListeners) { if (oldValue == null) - l.attributeAdded(event); + listener.attributeAdded(event); else if (value == null) - l.attributeRemoved(event); + listener.attributeRemoved(event); else - l.attributeReplaced(event); + listener.attributeReplaced(event); } } } @@ -2318,16 +2329,16 @@ else if (value == null) @Override public void removeAttribute(String name) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { Object oldValue = super.getAttribute(name); super.removeAttribute(name); if (oldValue != null && !_servletContextAttributeListeners.isEmpty()) { ServletContextAttributeEvent event = new ServletContextAttributeEvent(_scontext, name, oldValue); - for (ServletContextAttributeListener l : _servletContextAttributeListeners) + for (ServletContextAttributeListener listener : _servletContextAttributeListeners) { - l.attributeRemoved(event); + listener.attributeRemoved(event); } } } @@ -2371,11 +2382,9 @@ public void addListener(String className) try { - ClassLoader classLoader = ContextHandler.this.getClassLoader(); - @SuppressWarnings("unchecked") - Class clazz = classLoader == null - ? Loader.loadClass(className) - : (Class)classLoader.loadClass(className); + @SuppressWarnings( + {"unchecked", "rawtypes"}) + Class clazz = _classLoader == null ? Loader.loadClass(className) : (Class)_classLoader.loadClass(className); addListener(clazz); } catch (ClassNotFoundException e) @@ -2445,12 +2454,10 @@ public ClassLoader getClassLoader() if (!_enabled) throw new UnsupportedOperationException(); - ClassLoader classLoader = ContextHandler.this.getClassLoader(); - // no security manager just return the classloader if (!isUsingSecurityManager()) { - return classLoader; + return _classLoader; } else { @@ -2463,13 +2470,13 @@ public ClassLoader getClassLoader() ClassLoader callerLoader = caller.getCallerClassLoader(2); while (callerLoader != null) { - if (callerLoader == classLoader) - return classLoader; + if (callerLoader == _classLoader) + return _classLoader; else callerLoader = callerLoader.getParent(); } System.getSecurityManager().checkPermission(new RuntimePermission("getClassLoader")); - return classLoader; + return _classLoader; } } diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java index 1f76ee38da02..0418dbcdda03 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/DefaultSessionIdManager.java @@ -52,7 +52,9 @@ public class DefaultSessionIdManager extends ContainerLifeCycle implements SessionIdManager { private static final Logger LOG = LoggerFactory.getLogger(DefaultSessionIdManager.class); + public static final String __NEW_SESSION_ID = "org.eclipse.jetty.server.newSessionId"; + protected static final AtomicLong COUNTER = new AtomicLong(); private final AutoLock _lock = new AutoLock(); @@ -229,7 +231,7 @@ public String newSessionId(long seedTerm) // pick a new unique ID! String id = null; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { while (id == null || id.length() == 0) { @@ -268,7 +270,7 @@ public String newSessionId(long seedTerm) if (!StringUtil.isBlank(_workerName)) id = _workerName + id; - id = id + COUNTER.getAndIncrement(); + id = id + Long.toString(COUNTER.getAndIncrement()); } } return id; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java index d8626ed7eda8..7879aba64ee6 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/HouseKeeper.java @@ -127,7 +127,7 @@ else if (!_scheduler.isStarted()) */ protected void startScavenging() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_scheduler != null) { @@ -149,7 +149,7 @@ protected void startScavenging() throws Exception */ protected void stopScavenging() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_task != null) { @@ -170,7 +170,7 @@ protected void stopScavenging() throws Exception @Override protected void doStop() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { stopScavenging(); _scheduler = null; diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java b/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java index 89f953108bf0..05de2f9c69c6 100644 --- a/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java +++ b/jetty-server/src/main/java/org/eclipse/jetty/server/session/Session.java @@ -24,6 +24,7 @@ import java.util.Iterator; import java.util.Set; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSessionActivationListener; @@ -92,7 +93,8 @@ public enum IdState protected State _state = State.VALID; // state of the session:valid,invalid // or being invalidated - protected final AutoLock.WithCondition _lock = new AutoLock.WithCondition(); + protected AutoLock _lock = new AutoLock(); + protected Condition _stateChangeCompleted = _lock.newCondition(); protected boolean _resident = false; protected final SessionInactivityTimer _sessionInactivityTimer; @@ -121,7 +123,7 @@ public void onTimeoutExpired() long now = System.currentTimeMillis(); //handle what to do with the session after the timer expired getSessionHandler().sessionInactivityTimerExpired(Session.this, now); - try (AutoLock ignored = Session.this.lock()) + try (AutoLock l = Session.this.lock()) { //grab the lock and check what happened to the session: if it didn't get evicted and //it hasn't expired, we need to reset the timer @@ -206,7 +208,10 @@ public Session(SessionHandler handler, SessionData data) */ public long getRequests() { - return _lock.runLocked(() -> _requests); + try (AutoLock l = _lock.lock()) + { + return _requests; + } } public void setExtendedId(String extendedId) @@ -216,12 +221,15 @@ public void setExtendedId(String extendedId) protected void cookieSet() { - _lock.runLocked(() -> _sessionData.setCookieSet(_sessionData.getAccessed())); + try (AutoLock l = _lock.lock()) + { + _sessionData.setCookieSet(_sessionData.getAccessed()); + } } protected void use() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _requests++; @@ -234,7 +242,7 @@ protected void use() protected boolean access(long time) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (!isValid() || !isResident()) return false; @@ -254,7 +262,7 @@ protected boolean access(long time) protected void complete() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _requests--; @@ -281,7 +289,10 @@ protected void complete() */ protected boolean isExpiredAt(long time) { - return _lock.runLocked(() -> _sessionData.isExpiredAt(time)); + try (AutoLock l = _lock.lock()) + { + return _sessionData.isExpiredAt(time); + } } /** @@ -293,7 +304,10 @@ protected boolean isExpiredAt(long time) protected boolean isIdleLongerThan(int sec) { long now = System.currentTimeMillis(); - return _lock.runLocked(() -> (_sessionData.getAccessed() + (sec * 1000)) <= now); + try (AutoLock l = _lock.lock()) + { + return ((_sessionData.getAccessed() + (sec * 1000)) <= now); + } } /** @@ -399,23 +413,32 @@ public void willPassivate() public boolean isValid() { - return _lock.runLocked(() -> _state == State.VALID); + try (AutoLock l = _lock.lock()) + { + return _state == State.VALID; + } } public boolean isInvalid() { - return _lock.runLocked(() -> _state == State.INVALID || _state == State.INVALIDATING); + try (AutoLock l = _lock.lock()) + { + return _state == State.INVALID || _state == State.INVALIDATING; + } } public long getCookieSetTime() { - return _lock.runLocked(_sessionData::getCookieSet); + try (AutoLock l = _lock.lock()) + { + return _sessionData.getCookieSet(); + } } @Override public long getCreationTime() throws IllegalStateException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { checkValidForRead(); return _sessionData.getCreated(); @@ -425,7 +448,10 @@ public long getCreationTime() throws IllegalStateException @Override public String getId() { - return _lock.runLocked(_sessionData::getId); + try (AutoLock l = _lock.lock()) + { + return _sessionData.getId(); + } } public String getExtendedId() @@ -446,10 +472,12 @@ public String getVHost() @Override public long getLastAccessedTime() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (isInvalid()) + { throw new IllegalStateException("Session not valid"); + } return _sessionData.getLastAccessed(); } } @@ -465,7 +493,7 @@ public ServletContext getServletContext() @Override public void setMaxInactiveInterval(int secs) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _sessionData.setMaxInactiveMs((long)secs * 1000L); _sessionData.calcAndSetExpiry(); @@ -498,7 +526,7 @@ public long calculateInactivityTimeout(long now) { long time = 0; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { long remaining = _sessionData.getExpiry() - now; long maxInactive = _sessionData.getMaxInactiveMs(); @@ -559,7 +587,7 @@ else if (evictionPolicy == SessionCache.EVICT_ON_SESSION_EXIT) @Override public int getMaxInactiveInterval() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { long maxInactiveMs = _sessionData.getMaxInactiveMs(); return (int)(maxInactiveMs < 0 ? -1 : maxInactiveMs / 1000); @@ -627,7 +655,7 @@ protected void checkValidForRead() throws IllegalStateException @Override public Object getAttribute(String name) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { checkValidForRead(); return _sessionData.getAttribute(name); @@ -638,7 +666,7 @@ public Object getAttribute(String name) @Deprecated(since = "Servlet API 2.2") public Object getValue(String name) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { checkValidForRead(); return _sessionData.getAttribute(name); @@ -648,7 +676,7 @@ public Object getValue(String name) @Override public Enumeration getAttributeNames() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { checkValidForRead(); final Iterator itor = _sessionData.getKeys().iterator(); @@ -688,7 +716,7 @@ public Set getNames() @Deprecated(since = "Servlet API 2.2") public String[] getValueNames() throws IllegalStateException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { checkValidForRead(); Iterator itor = _sessionData.getKeys().iterator(); @@ -707,7 +735,7 @@ public String[] getValueNames() throws IllegalStateException public void setAttribute(String name, Object value) { Object old = null; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // if session is not valid, don't accept the set checkValidForWrite(); @@ -751,7 +779,7 @@ public void renewId(HttpServletRequest request) String id = null; String extendedId = null; - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { while (true) { @@ -764,7 +792,7 @@ public void renewId(HttpServletRequest request) case CHANGING: try { - lock.await(); + _stateChangeCompleted.await(); } catch (InterruptedException e) { @@ -787,7 +815,7 @@ public void renewId(HttpServletRequest request) String newId = _handler._sessionIdManager.renewSessionId(id, extendedId, request); - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { switch (_state) { @@ -805,7 +833,7 @@ public void renewId(HttpServletRequest request) setIdChanged(true); _state = State.VALID; - lock.signalAll(); + _stateChangeCompleted.signalAll(); break; case INVALID: @@ -877,7 +905,7 @@ protected boolean beginInvalidate() { boolean result = false; - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { while (true) { @@ -902,7 +930,7 @@ protected boolean beginInvalidate() { if (LOG.isDebugEnabled()) LOG.debug("Session {} waiting for id change to complete", _sessionData.getId()); - lock.await(); + _stateChangeCompleted.await(); } catch (InterruptedException e) { @@ -935,7 +963,7 @@ protected boolean beginInvalidate() */ protected void finishInvalidate() throws IllegalStateException { - try (AutoLock.WithCondition lock = _lock.lock()) + try (AutoLock l = _lock.lock()) { try { @@ -965,7 +993,7 @@ protected void finishInvalidate() throws IllegalStateException // mark as invalid _state = State.INVALID; _handler.recordSessionTime(this); - lock.signalAll(); + _stateChangeCompleted.signalAll(); } } } @@ -973,7 +1001,7 @@ protected void finishInvalidate() throws IllegalStateException @Override public boolean isNew() throws IllegalStateException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { checkValidForRead(); return _newSession; @@ -982,12 +1010,18 @@ public boolean isNew() throws IllegalStateException public void setIdChanged(boolean changed) { - _lock.runLocked(() -> _idChanged = changed); + try (AutoLock l = _lock.lock()) + { + _idChanged = changed; + } } public boolean isIdChanged() { - return _lock.runLocked(() -> _idChanged); + try (AutoLock l = _lock.lock()) + { + return _idChanged; + } } @Override @@ -1018,7 +1052,7 @@ public boolean isResident() @Override public String toString() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { return String.format("%s@%x{id=%s,x=%s,req=%d,res=%b}", getClass().getSimpleName(), diff --git a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java index 0593da48421c..1fbf01ca455c 100644 --- a/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java +++ b/jetty-server/src/test/java/org/eclipse/jetty/server/ServerConnectorTimeoutTest.java @@ -124,13 +124,16 @@ public void testIdleTimeoutAfterComplete() throws Exception private String process(String content) throws IOException, InterruptedException { - String request = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n"; + synchronized (this) + { + String request = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n"; - if (content == null) - request += "\r\n"; - else - request += "Content-Length: " + content.length() + "\r\n" + "\r\n" + content; - return getResponse(request); + if (content == null) + request += "\r\n"; + else + request += "Content-Length: " + content.length() + "\r\n" + "\r\n" + content; + return getResponse(request); + } } private String getResponse(String request) throws IOException, InterruptedException diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/BaseHolder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/BaseHolder.java index 084c37aefa49..2841fd09fece 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/BaseHolder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/BaseHolder.java @@ -173,7 +173,7 @@ protected void illegalStateIfContextStarted() protected void setInstance(T instance) { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { _instance = instance; if (instance == null) @@ -185,12 +185,15 @@ protected void setInstance(T instance) protected T getInstance() { - return _lock.runLocked(() -> _instance); + try (AutoLock l = lock()) + { + return _instance; + } } protected T createInstance() throws Exception { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { ServletContext ctx = getServletContext(); if (ctx == null) @@ -230,7 +233,10 @@ public ServletContext getServletContext() */ public boolean isInstance() { - return _lock.runLocked(() -> _instance != null); + try (AutoLock l = lock()) + { + return _instance != null; + } } @Override diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/FilterHolder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/FilterHolder.java index 044c3a2a6b67..a406635393bb 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/FilterHolder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/FilterHolder.java @@ -103,7 +103,7 @@ public void doStart() @Override public void initialize() throws Exception { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_filter != null) return; @@ -136,7 +136,7 @@ public void initialize() throws Exception @Override protected Filter createInstance() throws Exception { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { Filter filter = super.createInstance(); if (filter == null) diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Holder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Holder.java index b2afb37f8e0a..70e651d69e96 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Holder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Holder.java @@ -101,7 +101,7 @@ public String getName() @Override protected void setInstance(T instance) { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { super.setInstance(instance); if (getName() == null) diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java index 47bb32fc5281..ed360586b05c 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/Invoker.java @@ -164,7 +164,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) return; } - try (AutoLock ignored = _servletHandler.lock()) + try (AutoLock l = _servletHandler.lock()) { // find the entry for the invoker (me) _invokerEntry = _servletHandler.getMappedServlet(servletPath); @@ -176,7 +176,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) if (entry != null && !entry.equals(_invokerEntry)) { // Use the holder - holder = entry.getServletHolder(); + holder = (ServletHolder)entry.getServletHolder(); } else { diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ListenerHolder.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ListenerHolder.java index 754f9dba6a3e..971a4604433d 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ListenerHolder.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ListenerHolder.java @@ -108,7 +108,7 @@ public void doStart() throws Exception @Override protected EventListener createInstance() throws Exception { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { EventListener listener = super.createInstance(); if (listener == null) diff --git a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java index 5a6e63ed869c..ed3b4218f0b4 100644 --- a/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java +++ b/jetty-servlet/src/main/java/org/eclipse/jetty/servlet/ServletHandler.java @@ -81,7 +81,7 @@ *

* This handler does not implement the full J2EE features and is intended to * be used directly when a full web application is not required. If a Web application is required, - * then this handler should be used as part of a {@code org.eclipse.jetty.webapp.WebAppContext}. + * then this handler should be used as part of a org.eclipse.jetty.webapp.WebAppContext. *

* Unless run as part of a {@link ServletContextHandler} or derivative, the {@link #initialize()} * method must be called manually after start(). @@ -104,20 +104,32 @@ public class ServletHandler extends ScopedHandler private boolean _ensureDefaultServlet = true; private IdentityService _identityService; private boolean _allowDuplicateMappings = false; + private ServletHolder[] _servlets = new ServletHolder[0]; private ServletMapping[] _servletMappings; private final Map _filterNameMap = new HashMap<>(); private List _filterPathMappings; private MultiMap _filterNameMappings; + private final Map _servletNameMap = new HashMap<>(); private PathMappings _servletPathMap; + private ListenerHolder[] _listeners = new ListenerHolder[0]; private boolean _initialized = false; + @SuppressWarnings("unchecked") protected final ConcurrentMap[] _chainCache = new ConcurrentMap[FilterMapping.ALL]; + @SuppressWarnings("unchecked") protected final Queue[] _chainLRU = new Queue[FilterMapping.ALL]; + /** + * Constructor. + */ + public ServletHandler() + { + } + AutoLock lock() { return _lock.lock(); @@ -126,7 +138,7 @@ AutoLock lock() @Override public boolean isDumpable(Object o) { - return !(o instanceof BaseHolder || o instanceof FilterMapping || o instanceof ServletMapping); + return !(o instanceof Holder || o instanceof BaseHolder || o instanceof FilterMapping || o instanceof ServletMapping); } @Override @@ -143,48 +155,51 @@ public void dump(Appendable out, String indent) throws IOException @Override protected void doStart() throws Exception { - ContextHandler.Context context = ContextHandler.getCurrentContext(); - _servletContext = context == null ? new ContextHandler.StaticContext() : context; - _contextHandler = (ServletContextHandler)(context == null ? null : context.getContextHandler()); - - if (_contextHandler != null) + try (AutoLock l = lock()) { - SecurityHandler securityHandler = _contextHandler.getChildHandlerByClass(SecurityHandler.class); - if (securityHandler != null) - _identityService = securityHandler.getIdentityService(); - } + ContextHandler.Context context = ContextHandler.getCurrentContext(); + _servletContext = context == null ? new ContextHandler.StaticContext() : context; + _contextHandler = (ServletContextHandler)(context == null ? null : context.getContextHandler()); - updateNameMappings(); - updateMappings(); + if (_contextHandler != null) + { + SecurityHandler securityHandler = _contextHandler.getChildHandlerByClass(SecurityHandler.class); + if (securityHandler != null) + _identityService = securityHandler.getIdentityService(); + } - if (getServletMapping("/") == null && isEnsureDefaultServlet()) - { - if (LOG.isDebugEnabled()) - LOG.debug("Adding Default404Servlet to {}", this); - addServletWithMapping(Default404Servlet.class, "/"); + updateNameMappings(); updateMappings(); - getServletMapping("/").setFromDefaultDescriptor(true); - } - if (isFilterChainsCached()) - { - _chainCache[FilterMapping.REQUEST] = new ConcurrentHashMap<>(); - _chainCache[FilterMapping.FORWARD] = new ConcurrentHashMap<>(); - _chainCache[FilterMapping.INCLUDE] = new ConcurrentHashMap<>(); - _chainCache[FilterMapping.ERROR] = new ConcurrentHashMap<>(); - _chainCache[FilterMapping.ASYNC] = new ConcurrentHashMap<>(); - - _chainLRU[FilterMapping.REQUEST] = new ConcurrentLinkedQueue<>(); - _chainLRU[FilterMapping.FORWARD] = new ConcurrentLinkedQueue<>(); - _chainLRU[FilterMapping.INCLUDE] = new ConcurrentLinkedQueue<>(); - _chainLRU[FilterMapping.ERROR] = new ConcurrentLinkedQueue<>(); - _chainLRU[FilterMapping.ASYNC] = new ConcurrentLinkedQueue<>(); - } + if (getServletMapping("/") == null && isEnsureDefaultServlet()) + { + if (LOG.isDebugEnabled()) + LOG.debug("Adding Default404Servlet to {}", this); + addServletWithMapping(Default404Servlet.class, "/"); + updateMappings(); + getServletMapping("/").setFromDefaultDescriptor(true); + } - if (_contextHandler == null) - initialize(); + if (isFilterChainsCached()) + { + _chainCache[FilterMapping.REQUEST] = new ConcurrentHashMap<>(); + _chainCache[FilterMapping.FORWARD] = new ConcurrentHashMap<>(); + _chainCache[FilterMapping.INCLUDE] = new ConcurrentHashMap<>(); + _chainCache[FilterMapping.ERROR] = new ConcurrentHashMap<>(); + _chainCache[FilterMapping.ASYNC] = new ConcurrentHashMap<>(); + + _chainLRU[FilterMapping.REQUEST] = new ConcurrentLinkedQueue<>(); + _chainLRU[FilterMapping.FORWARD] = new ConcurrentLinkedQueue<>(); + _chainLRU[FilterMapping.INCLUDE] = new ConcurrentLinkedQueue<>(); + _chainLRU[FilterMapping.ERROR] = new ConcurrentLinkedQueue<>(); + _chainLRU[FilterMapping.ASYNC] = new ConcurrentLinkedQueue<>(); + } + + if (_contextHandler == null) + initialize(); - super.doStart(); + super.doStart(); + } } /** @@ -226,115 +241,118 @@ protected void stop(LifeCycle l) throws Exception @Override protected void doStop() throws Exception { - super.doStop(); - - // Stop filters - List filterHolders = new ArrayList<>(); - List filterMappings = ArrayUtil.asMutableList(_filterMappings); - if (_filters != null) + try (AutoLock l = lock()) { - for (int i = _filters.length; i-- > 0; ) + super.doStop(); + + // Stop filters + List filterHolders = new ArrayList<>(); + List filterMappings = ArrayUtil.asMutableList(_filterMappings); + if (_filters != null) { - FilterHolder filter = _filters[i]; - try + for (int i = _filters.length; i-- > 0; ) { - filter.stop(); - } - catch (Exception e) - { - LOG.warn("Unable to stop filter {}", filter, e); - } - if (filter.getSource() != Source.EMBEDDED) - { - //remove all of the mappings that were for non-embedded filters - _filterNameMap.remove(filter.getName()); - //remove any mappings associated with this filter - filterMappings.removeIf(fm -> fm.getFilterName().equals(filter.getName())); + FilterHolder filter = _filters[i]; + try + { + filter.stop(); + } + catch (Exception e) + { + LOG.warn("Unable to stop filter {}", filter, e); + } + if (filter.getSource() != Source.EMBEDDED) + { + //remove all of the mappings that were for non-embedded filters + _filterNameMap.remove(filter.getName()); + //remove any mappings associated with this filter + filterMappings.removeIf(fm -> fm.getFilterName().equals(filter.getName())); + } + else + filterHolders.add(filter); //only retain embedded } - else - filterHolders.add(filter); //only retain embedded } - } - //Retain only filters and mappings that were added using jetty api (ie Source.EMBEDDED) - FilterHolder[] fhs = (FilterHolder[])LazyList.toArray(filterHolders, FilterHolder.class); - updateBeans(_filters, fhs); - _filters = fhs; - FilterMapping[] fms = (FilterMapping[])LazyList.toArray(filterMappings, FilterMapping.class); - updateBeans(_filterMappings, fms); - _filterMappings = fms; - - _matchAfterIndex = (_filterMappings == null || _filterMappings.length == 0 ? -1 : _filterMappings.length - 1); - _matchBeforeIndex = -1; - - // Stop servlets - List servletHolders = new ArrayList<>(); //will be remaining servlets - List servletMappings = ArrayUtil.asMutableList(_servletMappings); //will be remaining mappings - if (_servlets != null) - { - for (int i = _servlets.length; i-- > 0; ) + //Retain only filters and mappings that were added using jetty api (ie Source.EMBEDDED) + FilterHolder[] fhs = (FilterHolder[])LazyList.toArray(filterHolders, FilterHolder.class); + updateBeans(_filters, fhs); + _filters = fhs; + FilterMapping[] fms = (FilterMapping[])LazyList.toArray(filterMappings, FilterMapping.class); + updateBeans(_filterMappings, fms); + _filterMappings = fms; + + _matchAfterIndex = (_filterMappings == null || _filterMappings.length == 0 ? -1 : _filterMappings.length - 1); + _matchBeforeIndex = -1; + + // Stop servlets + List servletHolders = new ArrayList<>(); //will be remaining servlets + List servletMappings = ArrayUtil.asMutableList(_servletMappings); //will be remaining mappings + if (_servlets != null) { - ServletHolder servlet = _servlets[i]; - try - { - servlet.stop(); - } - catch (Exception e) + for (int i = _servlets.length; i-- > 0; ) { - LOG.warn("Unable to stop servlet {}", servlet, e); - } + ServletHolder servlet = _servlets[i]; + try + { + servlet.stop(); + } + catch (Exception e) + { + LOG.warn("Unable to stop servlet {}", servlet, e); + } - if (servlet.getSource() != Source.EMBEDDED) - { - //remove from servlet name map - _servletNameMap.remove(servlet.getName()); - //remove any mappings associated with this servlet - servletMappings.removeIf(sm -> sm.getServletName().equals(servlet.getName())); + if (servlet.getSource() != Source.EMBEDDED) + { + //remove from servlet name map + _servletNameMap.remove(servlet.getName()); + //remove any mappings associated with this servlet + servletMappings.removeIf(sm -> sm.getServletName().equals(servlet.getName())); + } + else + servletHolders.add(servlet); //only retain embedded } - else - servletHolders.add(servlet); //only retain embedded } - } - //Retain only Servlets and mappings added via jetty apis (ie Source.EMBEDDED) - ServletHolder[] shs = (ServletHolder[])LazyList.toArray(servletHolders, ServletHolder.class); - updateBeans(_servlets, shs); - _servlets = shs; - ServletMapping[] sms = (ServletMapping[])LazyList.toArray(servletMappings, ServletMapping.class); - updateBeans(_servletMappings, sms); - _servletMappings = sms; - - if (_contextHandler != null) - _contextHandler.contextDestroyed(); + //Retain only Servlets and mappings added via jetty apis (ie Source.EMBEDDED) + ServletHolder[] shs = (ServletHolder[])LazyList.toArray(servletHolders, ServletHolder.class); + updateBeans(_servlets, shs); + _servlets = shs; + ServletMapping[] sms = (ServletMapping[])LazyList.toArray(servletMappings, ServletMapping.class); + updateBeans(_servletMappings, sms); + _servletMappings = sms; - //Retain only Listeners added via jetty apis (is Source.EMBEDDED) - List listenerHolders = new ArrayList<>(); - if (_listeners != null) - { - for (int i = _listeners.length; i-- > 0; ) + if (_contextHandler != null) + _contextHandler.contextDestroyed(); + + //Retain only Listeners added via jetty apis (is Source.EMBEDDED) + List listenerHolders = new ArrayList<>(); + if (_listeners != null) { - ListenerHolder listener = _listeners[i]; - try + for (int i = _listeners.length; i-- > 0; ) { - listener.stop(); - } - catch (Exception e) - { - LOG.warn("Unable to stop listener {}", listener, e); + ListenerHolder listener = _listeners[i]; + try + { + listener.stop(); + } + catch (Exception e) + { + LOG.warn("Unable to stop listener {}", listener, e); + } + if (listener.getSource() == Source.EMBEDDED) + listenerHolders.add(listener); } - if (listener.getSource() == Source.EMBEDDED) - listenerHolders.add(listener); } + ListenerHolder[] listeners = (ListenerHolder[])LazyList.toArray(listenerHolders, ListenerHolder.class); + updateBeans(_listeners, listeners); + _listeners = listeners; + + //will be regenerated on next start + _filterPathMappings = null; + _filterNameMappings = null; + _servletPathMap = null; + _initialized = false; } - ListenerHolder[] listeners = (ListenerHolder[])LazyList.toArray(listenerHolders, ListenerHolder.class); - updateBeans(_listeners, listeners); - _listeners = listeners; - - //will be regenerated on next start - _filterPathMappings = null; - _filterNameMappings = null; - _servletPathMap = null; - _initialized = false; } protected IdentityService getIdentityService() @@ -858,7 +876,7 @@ public void addServletWithMapping(ServletHolder servlet, String pathSpec) try { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (servlet != null && !containsServletHolder(servlet)) setServlets(ArrayUtil.addToArray(holders, servlet, ServletHolder.class)); @@ -886,7 +904,7 @@ public void addServlet(ServletHolder holder) if (holder == null) return; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (!containsServletHolder(holder)) setServlets(ArrayUtil.addToArray(getServlets(), holder, ServletHolder.class)); @@ -971,7 +989,7 @@ public void addFilterWithMapping(FilterHolder holder, String pathSpec, EnumSet(); @@ -273,7 +273,7 @@ public void setUserRoleLink(String name, String link) */ public String getUserRoleLink(String name) { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_roleMap == null) return name; @@ -399,7 +399,7 @@ public void doStart() _config = new Config(); - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (getHeldClass() != null && javax.servlet.SingleThreadModel.class.isAssignableFrom(getHeldClass())) _servlet = new SingleThreadedWrapper(); @@ -410,7 +410,7 @@ public void doStart() public void initialize() throws Exception { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_servlet == null && (_initOnStartup || isInstance())) { @@ -424,7 +424,7 @@ public void initialize() public void doStop() throws Exception { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { Servlet servlet = _servlet; if (servlet != null) @@ -470,7 +470,7 @@ public void destroyInstance(Object o) public Servlet getServlet() throws ServletException { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_servlet == null && isRunning()) { @@ -531,7 +531,7 @@ private void checkInitOnStartup() private Servlet makeUnavailable(UnavailableException e) { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { _servlet = new UnavailableServlet(e, _servlet); return _servlet; @@ -562,7 +562,7 @@ private void makeUnavailable(final Throwable e) private void initServlet() throws ServletException { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_servlet == null) _servlet = getInstance(); @@ -1016,12 +1016,12 @@ public ServletRegistration.Dynamic getRegistration() private class SingleThreadedWrapper implements Servlet { - private final Stack _stack = new Stack<>(); + Stack _stack = new Stack<>(); @Override public void destroy() { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { while (_stack.size() > 0) { @@ -1053,7 +1053,7 @@ public String getServletInfo() @Override public void init(ServletConfig config) throws ServletException { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_stack.size() == 0) { @@ -1079,10 +1079,10 @@ public void init(ServletConfig config) throws ServletException public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { Servlet s; - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { if (_stack.size() > 0) - s = _stack.pop(); + s = (Servlet)_stack.pop(); else { try @@ -1107,7 +1107,7 @@ public void service(ServletRequest req, ServletResponse res) throws ServletExcep } finally { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { _stack.push(s); } @@ -1131,7 +1131,7 @@ protected Servlet newInstance() throws Exception @Override protected Servlet createInstance() throws Exception { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { Servlet servlet = super.createInstance(); if (servlet == null) @@ -1205,7 +1205,7 @@ else if (System.nanoTime() < _available) ((HttpServletResponse)res).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); else { - try (AutoLock ignored = lock()) + try (AutoLock l = lock()) { ServletHolder.this._servlet = this._servlet; _servlet.service(req, res); diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/DoSFilter.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/DoSFilter.java index ab11987faafd..60373ccb692b 100644 --- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/DoSFilter.java +++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/DoSFilter.java @@ -1154,7 +1154,7 @@ public RateTracker(ServletContext context, String filterName, String id, int typ public boolean isRateExceeded(long now) { final long last; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { last = _timestamps[_next]; _timestamps[_next] = now; @@ -1283,7 +1283,7 @@ public boolean isRateExceeded(long now) // rate limit is never exceeded, but we keep track of the request timestamps // so that we know whether there was recent activity on this tracker // and whether it should be expired - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _timestamps[_next] = now; _next = (_next + 1) % _timestamps.length; diff --git a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/EventSourceServlet.java b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/EventSourceServlet.java index 376c7d5eeb32..10a81b87e625 100644 --- a/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/EventSourceServlet.java +++ b/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/EventSourceServlet.java @@ -44,11 +44,11 @@ * and to emit event source events.

*

This servlet supports the following configuration parameters:

*
    - *
  • {@code heartBeatPeriod}, that specifies the heartbeat period, in seconds, used to check + *
  • heartBeatPeriod, that specifies the heartbeat period, in seconds, used to check * whether the connection has been closed by the client; defaults to 10 seconds.
  • *
* - *

NOTE: there is currently no support for {@code last-event-id}.

+ *

NOTE: there is currently no support for last-event-id.

*/ public abstract class EventSourceServlet extends HttpServlet { @@ -79,6 +79,7 @@ public void destroy() @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + @SuppressWarnings("unchecked") Enumeration acceptValues = request.getHeaders("Accept"); while (acceptValues.hasMoreElements()) { @@ -145,7 +146,7 @@ public EventSourceEmitter(EventSource eventSource, AsyncContext async) throws IO @Override public void event(String name, String data) throws IOException { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { output.write(EVENT_FIELD); output.write(name.getBytes(StandardCharsets.UTF_8)); @@ -157,7 +158,7 @@ public void event(String name, String data) throws IOException @Override public void data(String data) throws IOException { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { BufferedReader reader = new BufferedReader(new StringReader(data)); String line; @@ -175,7 +176,7 @@ public void data(String data) throws IOException @Override public void comment(String comment) throws IOException { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { output.write(COMMENT_FIELD); output.write(comment.getBytes(StandardCharsets.UTF_8)); @@ -193,7 +194,7 @@ public void run() // on the second flush() try { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { output.write('\r'); flush(); @@ -219,7 +220,7 @@ protected void flush() throws IOException @Override public void close() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { closed = true; heartBeat.cancel(false); @@ -229,7 +230,7 @@ public void close() private void scheduleHeartBeat() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (!closed) heartBeat = scheduler.schedule(this, heartBeatPeriod, TimeUnit.SECONDS); diff --git a/jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONDateConvertor.java b/jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONDateConvertor.java index a3d63a0941d0..111df72e89fd 100644 --- a/jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONDateConvertor.java +++ b/jetty-util-ajax/src/main/java/org/eclipse/jetty/util/ajax/JSONDateConvertor.java @@ -79,7 +79,7 @@ public Object fromJSON(Map map) throw new UnsupportedOperationException(); try { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { return _format.parseObject((String)map.get("value")); } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java b/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java index c91fd47915bb..ba150d0c11e8 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java @@ -229,7 +229,7 @@ void setFile(ZonedDateTime now) File oldFile = null; File newFile = null; File backupFile = null; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // Check directory File file = new File(_filename); @@ -345,7 +345,7 @@ void removeOldFiles(ZonedDateTime now) @Override public void write(int b) throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _out.write(b); } @@ -354,7 +354,7 @@ public void write(int b) throws IOException @Override public void write(byte[] buf) throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _out.write(buf); } @@ -363,7 +363,7 @@ public void write(byte[] buf) throws IOException @Override public void write(byte[] buf, int off, int len) throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _out.write(buf, off, len); } @@ -372,7 +372,7 @@ public void write(byte[] buf, int off, int len) throws IOException @Override public void flush() throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _out.flush(); } @@ -381,7 +381,7 @@ public void flush() throws IOException @Override public void close() throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { try { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/Scanner.java b/jetty-util/src/main/java/org/eclipse/jetty/util/Scanner.java index 9a28572269e4..8642da621cdb 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/Scanner.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/Scanner.java @@ -68,13 +68,13 @@ public class Scanner extends AbstractLifeCycle private static int __scannerId = 0; private final AutoLock _lock = new AutoLock(); + private int _scanInterval; + private int _scanCount = 0; private final List _listeners = new ArrayList<>(); private final Map _prevScan = new HashMap<>(); private final Map _currentScan = new HashMap<>(); - private final Map> _scannables = new HashMap<>(); - private int _scanInterval; - private int _scanCount = 0; private FilenameFilter _filter; + private final Map> _scannables = new HashMap<>(); private volatile boolean _running = false; private boolean _reportExisting = true; private boolean _reportDirs = true; @@ -300,7 +300,10 @@ public Scanner() */ public int getScanInterval() { - return _lock.runLocked(() -> _scanInterval); + try (AutoLock l = _lock.lock()) + { + return _scanInterval; + } } /** @@ -310,7 +313,7 @@ public int getScanInterval() */ public void setScanInterval(int scanInterval) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _scanInterval = scanInterval; schedule(); @@ -334,7 +337,7 @@ public void addScanDir(File dir) { if (dir == null) return; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (dir.isDirectory()) addDirectory(dir.toPath()); @@ -357,10 +360,15 @@ public void addFile(Path p) throws IOException { if (p == null) throw new IllegalStateException("Null path"); + File f = p.toFile(); if (!f.exists() || f.isDirectory()) throw new IllegalStateException("Not file or doesn't exist: " + f.getCanonicalPath()); - _lock.runLocked(() -> _scannables.put(p, null)); + + try (AutoLock l = _lock.lock()) + { + _scannables.put(p, null); + } } /** @@ -374,11 +382,12 @@ public IncludeExcludeSet addDirectory(Path p) throws IOExcept { if (p == null) throw new IllegalStateException("Null path"); + File f = p.toFile(); if (!f.exists() || !f.isDirectory()) throw new IllegalStateException("Not directory or doesn't exist: " + f.getCanonicalPath()); - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { IncludeExcludeSet includesExcludes = _scannables.get(p); if (includesExcludes == null) @@ -508,7 +517,10 @@ public void addListener(Listener listener) { if (listener == null) return; - _lock.runLocked(() -> _listeners.add(listener)); + try (AutoLock l = _lock.lock()) + { + _listeners.add(listener); + } } /** @@ -520,7 +532,10 @@ public void removeListener(Listener listener) { if (listener == null) return; - _lock.runLocked(() -> _listeners.remove(listener)); + try (AutoLock l = _lock.lock()) + { + _listeners.remove(listener); + } } /** @@ -529,7 +544,7 @@ public void removeListener(Listener listener) @Override public void doStart() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_running) return; @@ -595,7 +610,7 @@ public void schedule() @Override public void doStop() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_running) { @@ -646,7 +661,7 @@ public boolean exists(String path) */ public void scan() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { reportScanStart(++_scanCount); scanFiles(); @@ -655,12 +670,12 @@ public void scan() _prevScan.putAll(_currentScan); reportScanEnd(_scanCount); - for (Listener l : _listeners) + for (Listener listener : _listeners) { try { - if (l instanceof ScanListener) - ((ScanListener)l).scan(); + if (listener instanceof ScanListener) + ((ScanListener)listener).scan(); } catch (Throwable e) { @@ -675,7 +690,7 @@ public void scan() */ public void scanFiles() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _currentScan.clear(); for (Path p : _scannables.keySet()) @@ -700,7 +715,7 @@ public void scanFiles() */ private void reportDifferences(Map currentScan, Map oldScan) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // scan the differences and add what was found to the map of notifications: Set oldScanKeys = new HashSet<>(oldScan.keySet()); diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java b/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java index 9b08454e42f7..77aebf337794 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/StringUtil.java @@ -376,12 +376,15 @@ public static void append(StringBuilder buf, int offset, int length) { - int end = offset + length; - for (int i = offset; i < end; i++) + synchronized (buf) { - if (i >= s.length()) - break; - buf.append(s.charAt(i)); + int end = offset + length; + for (int i = offset; i < end; i++) + { + if (i >= s.length()) + break; + buf.append(s.charAt(i)); + } } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/URIUtil.java b/jetty-util/src/main/java/org/eclipse/jetty/util/URIUtil.java index fa381aa9dbc2..c7c88b09b673 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/URIUtil.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/URIUtil.java @@ -1180,24 +1180,27 @@ public static void appendSchemeHostPort(StringBuilder url, String scheme, String */ public static void appendSchemeHostPort(StringBuffer url, String scheme, String server, int port) { - url.append(scheme).append("://").append(HostPort.normalizeHost(server)); - - if (port > 0) + synchronized (url) { - switch (scheme) + url.append(scheme).append("://").append(HostPort.normalizeHost(server)); + + if (port > 0) { - case "http": - if (port != 80) - url.append(':').append(port); - break; + switch (scheme) + { + case "http": + if (port != 80) + url.append(':').append(port); + break; - case "https": - if (port != 443) - url.append(':').append(port); - break; + case "https": + if (port != 443) + url.append(':').append(port); + break; - default: - url.append(':').append(port); + default: + url.append(':').append(port); + } } } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java b/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java index 906d72ee8f3e..32ff9592f672 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/UrlEncoded.java @@ -140,7 +140,7 @@ public String encode(Charset charset) * for parameters without a value. e.g. "blah?a=&b=&c=". * @return the MultiMap as a string encoded with % encodings */ - public String encode(Charset charset, boolean equalsForNullValue) + public synchronized String encode(Charset charset, boolean equalsForNullValue) { return encode(this, charset, equalsForNullValue); } @@ -238,61 +238,64 @@ public static void decodeTo(String content, MultiMap map, Charset charse return; } - String key = null; - String value; - int mark = -1; - boolean encoded = false; - for (int i = 0; i < content.length(); i++) + synchronized (map) { - char c = content.charAt(i); - switch (c) + String key = null; + String value; + int mark = -1; + boolean encoded = false; + for (int i = 0; i < content.length(); i++) { - case '&': - int l = i - mark - 1; - value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l, charset) : content.substring(mark + 1, i)); - mark = i; - encoded = false; - if (key != null) - { - map.add(key, value); - } - else if (value != null && value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - break; - case '=': - if (key != null) + char c = content.charAt(i); + switch (c) + { + case '&': + int l = i - mark - 1; + value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l, charset) : content.substring(mark + 1, i)); + mark = i; + encoded = false; + if (key != null) + { + map.add(key, value); + } + else if (value != null && value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; break; - key = encoded ? decodeString(content, mark + 1, i - mark - 1, charset) : content.substring(mark + 1, i); - mark = i; - encoded = false; - break; - case '+': - encoded = true; - break; - case '%': - encoded = true; - break; + case '=': + if (key != null) + break; + key = encoded ? decodeString(content, mark + 1, i - mark - 1, charset) : content.substring(mark + 1, i); + mark = i; + encoded = false; + break; + case '+': + encoded = true; + break; + case '%': + encoded = true; + break; + } } - } - if (key != null) - { - int l = content.length() - mark - 1; - value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l, charset) : content.substring(mark + 1)); - map.add(key, value); - } - else if (mark < content.length()) - { - key = encoded - ? decodeString(content, mark + 1, content.length() - mark - 1, charset) - : content.substring(mark + 1); - if (key != null && key.length() > 0) + if (key != null) + { + int l = content.length() - mark - 1; + value = l == 0 ? "" : (encoded ? decodeString(content, mark + 1, l, charset) : content.substring(mark + 1)); + map.add(key, value); + } + else if (mark < content.length()) { - map.add(key, ""); + key = encoded + ? decodeString(content, mark + 1, content.length() - mark - 1, charset) + : content.substring(mark + 1); + if (key != null && key.length() > 0) + { + map.add(key, ""); + } } } } @@ -313,72 +316,75 @@ public static void decodeUtf8To(String query, MultiMap map) public static void decodeUtf8To(String query, int offset, int length, MultiMap map) { Utf8StringBuilder buffer = new Utf8StringBuilder(); - String key = null; - String value = null; - - int end = offset + length; - for (int i = offset; i < end; i++) + synchronized (map) { - char c = query.charAt(i); - switch (c) + String key = null; + String value = null; + + int end = offset + length; + for (int i = offset; i < end; i++) { - case '&': - value = buffer.toReplacedString(); - buffer.reset(); - if (key != null) - { - map.add(key, value); - } - else if (value != null && value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - break; + char c = query.charAt(i); + switch (c) + { + case '&': + value = buffer.toReplacedString(); + buffer.reset(); + if (key != null) + { + map.add(key, value); + } + else if (value != null && value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + break; - case '=': - if (key != null) - { - buffer.append(c); + case '=': + if (key != null) + { + buffer.append(c); + break; + } + key = buffer.toReplacedString(); + buffer.reset(); break; - } - key = buffer.toReplacedString(); - buffer.reset(); - break; - case '+': - buffer.append((byte)' '); - break; + case '+': + buffer.append((byte)' '); + break; - case '%': - if (i + 2 < end) - { - char hi = query.charAt(++i); - char lo = query.charAt(++i); - buffer.append(decodeHexByte(hi, lo)); - } - else - { - throw new Utf8Appendable.NotUtf8Exception("Incomplete % encoding"); - } - break; + case '%': + if (i + 2 < end) + { + char hi = query.charAt(++i); + char lo = query.charAt(++i); + buffer.append(decodeHexByte(hi, lo)); + } + else + { + throw new Utf8Appendable.NotUtf8Exception("Incomplete % encoding"); + } + break; - default: - buffer.append(c); - break; + default: + buffer.append(c); + break; + } } - } - if (key != null) - { - value = buffer.toReplacedString(); - buffer.reset(); - map.add(key, value); - } - else if (buffer.length() > 0) - { - map.add(buffer.toReplacedString(), ""); + if (key != null) + { + value = buffer.toReplacedString(); + buffer.reset(); + map.add(key, value); + } + else if (buffer.length() > 0) + { + map.add(buffer.toReplacedString(), ""); + } } } @@ -394,71 +400,74 @@ else if (buffer.length() > 0) public static void decode88591To(InputStream in, MultiMap map, int maxLength, int maxKeys) throws IOException { - StringBuilder buffer = new StringBuilder(); - String key = null; - String value = null; + synchronized (map) + { + StringBuilder buffer = new StringBuilder(); + String key = null; + String value = null; - int b; + int b; - int totalLength = 0; - while ((b = in.read()) >= 0) - { - switch ((char)b) + int totalLength = 0; + while ((b = in.read()) >= 0) { - case '&': - value = buffer.length() == 0 ? "" : buffer.toString(); - buffer.setLength(0); - if (key != null) - { - map.add(key, value); - } - else if (value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - checkMaxKeys(map, maxKeys); - break; + switch ((char)b) + { + case '&': + value = buffer.length() == 0 ? "" : buffer.toString(); + buffer.setLength(0); + if (key != null) + { + map.add(key, value); + } + else if (value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + checkMaxKeys(map, maxKeys); + break; - case '=': - if (key != null) - { - buffer.append((char)b); + case '=': + if (key != null) + { + buffer.append((char)b); + break; + } + key = buffer.toString(); + buffer.setLength(0); break; - } - key = buffer.toString(); - buffer.setLength(0); - break; - case '+': - buffer.append(' '); - break; + case '+': + buffer.append(' '); + break; - case '%': - int code0 = in.read(); - int code1 = in.read(); - buffer.append(decodeHexChar(code0, code1)); - break; + case '%': + int code0 = in.read(); + int code1 = in.read(); + buffer.append(decodeHexChar(code0, code1)); + break; - default: - buffer.append((char)b); - break; + default: + buffer.append((char)b); + break; + } + checkMaxLength(++totalLength, maxLength); } - checkMaxLength(++totalLength, maxLength); - } - if (key != null) - { - value = buffer.length() == 0 ? "" : buffer.toString(); - buffer.setLength(0); - map.add(key, value); - } - else if (buffer.length() > 0) - { - map.add(buffer.toString(), ""); + if (key != null) + { + value = buffer.length() == 0 ? "" : buffer.toString(); + buffer.setLength(0); + map.add(key, value); + } + else if (buffer.length() > 0) + { + map.add(buffer.toString(), ""); + } + checkMaxKeys(map, maxKeys); } - checkMaxKeys(map, maxKeys); } /** @@ -473,71 +482,74 @@ else if (buffer.length() > 0) public static void decodeUtf8To(InputStream in, MultiMap map, int maxLength, int maxKeys) throws IOException { - Utf8StringBuilder buffer = new Utf8StringBuilder(); - String key = null; - String value = null; + synchronized (map) + { + Utf8StringBuilder buffer = new Utf8StringBuilder(); + String key = null; + String value = null; - int b; + int b; - int totalLength = 0; - while ((b = in.read()) >= 0) - { - switch ((char)b) + int totalLength = 0; + while ((b = in.read()) >= 0) { - case '&': - value = buffer.toReplacedString(); - buffer.reset(); - if (key != null) - { - map.add(key, value); - } - else if (value != null && value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - checkMaxKeys(map, maxKeys); - break; + switch ((char)b) + { + case '&': + value = buffer.toReplacedString(); + buffer.reset(); + if (key != null) + { + map.add(key, value); + } + else if (value != null && value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + checkMaxKeys(map, maxKeys); + break; - case '=': - if (key != null) - { + case '=': + if (key != null) + { + buffer.append((byte)b); + break; + } + key = buffer.toReplacedString(); + buffer.reset(); + break; + + case '+': + buffer.append((byte)' '); + break; + + case '%': + char code0 = (char)in.read(); + char code1 = (char)in.read(); + buffer.append(decodeHexByte(code0, code1)); + break; + + default: buffer.append((byte)b); break; - } - key = buffer.toReplacedString(); - buffer.reset(); - break; - - case '+': - buffer.append((byte)' '); - break; - - case '%': - char code0 = (char)in.read(); - char code1 = (char)in.read(); - buffer.append(decodeHexByte(code0, code1)); - break; - - default: - buffer.append((byte)b); - break; + } + checkMaxLength(++totalLength, maxLength); } - checkMaxLength(++totalLength, maxLength); - } - if (key != null) - { - value = buffer.toReplacedString(); - buffer.reset(); - map.add(key, value); - } - else if (buffer.length() > 0) - { - map.add(buffer.toReplacedString(), ""); + if (key != null) + { + value = buffer.toReplacedString(); + buffer.reset(); + map.add(key, value); + } + else if (buffer.length() > 0) + { + map.add(buffer.toReplacedString(), ""); + } + checkMaxKeys(map, maxKeys); } - checkMaxKeys(map, maxKeys); } public static void decodeUtf16To(InputStream in, MultiMap map, int maxLength, int maxKeys) throws IOException @@ -615,74 +627,77 @@ public static void decodeTo(InputStream in, MultiMap map, Charset charse return; } - String key = null; - String value = null; - - int c; + synchronized (map) + { + String key = null; + String value = null; - int totalLength = 0; + int c; - try (ByteArrayOutputStream2 output = new ByteArrayOutputStream2()) - { - int size = 0; + int totalLength = 0; - while ((c = in.read()) > 0) + try (ByteArrayOutputStream2 output = new ByteArrayOutputStream2()) { - switch ((char)c) + int size = 0; + + while ((c = in.read()) > 0) { - case '&': - size = output.size(); - value = size == 0 ? "" : output.toString(charset); - output.setCount(0); - if (key != null) - { - map.add(key, value); - } - else if (value != null && value.length() > 0) - { - map.add(value, ""); - } - key = null; - value = null; - checkMaxKeys(map, maxKeys); - break; - case '=': - if (key != null) - { + switch ((char)c) + { + case '&': + size = output.size(); + value = size == 0 ? "" : output.toString(charset); + output.setCount(0); + if (key != null) + { + map.add(key, value); + } + else if (value != null && value.length() > 0) + { + map.add(value, ""); + } + key = null; + value = null; + checkMaxKeys(map, maxKeys); + break; + case '=': + if (key != null) + { + output.write(c); + break; + } + size = output.size(); + key = size == 0 ? "" : output.toString(charset); + output.setCount(0); + break; + case '+': + output.write(' '); + break; + case '%': + int code0 = in.read(); + int code1 = in.read(); + output.write(decodeHexChar(code0, code1)); + break; + default: output.write(c); break; - } - size = output.size(); - key = size == 0 ? "" : output.toString(charset); - output.setCount(0); - break; - case '+': - output.write(' '); - break; - case '%': - int code0 = in.read(); - int code1 = in.read(); - output.write(decodeHexChar(code0, code1)); - break; - default: - output.write(c); - break; + } + checkMaxLength(++totalLength, maxLength); } - checkMaxLength(++totalLength, maxLength); - } - size = output.size(); - if (key != null) - { - value = size == 0 ? "" : output.toString(charset); - output.setCount(0); - map.add(key, value); - } - else if (size > 0) - { - map.add(output.toString(charset), ""); + size = output.size(); + if (key != null) + { + value = size == 0 ? "" : output.toString(charset); + output.setCount(0); + map.add(key, value); + } + else if (size > 0) + { + map.add(output.toString(charset), ""); + } + checkMaxKeys(map, maxKeys); } - checkMaxKeys(map, maxKeys); } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/component/AbstractLifeCycle.java b/jetty-util/src/main/java/org/eclipse/jetty/util/component/AbstractLifeCycle.java index ccc7d68c48b6..a7b37d0e2a0b 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/component/AbstractLifeCycle.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/component/AbstractLifeCycle.java @@ -77,7 +77,7 @@ protected void doStop() throws Exception @Override public final void start() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { try { @@ -118,7 +118,7 @@ public final void start() throws Exception @Override public final void stop() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { try { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/component/AttributeContainerMap.java b/jetty-util/src/main/java/org/eclipse/jetty/util/component/AttributeContainerMap.java index f6165e9bc325..391ed572e189 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/component/AttributeContainerMap.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/component/AttributeContainerMap.java @@ -39,7 +39,7 @@ public class AttributeContainerMap extends ContainerLifeCycle implements Attribu @Override public void setAttribute(String name, Object attribute) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { Object old = _map.put(name, attribute); updateBean(old, attribute); @@ -49,7 +49,7 @@ public void setAttribute(String name, Object attribute) @Override public void removeAttribute(String name) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { Object removed = _map.remove(name); if (removed != null) @@ -60,25 +60,34 @@ public void removeAttribute(String name) @Override public Object getAttribute(String name) { - return _lock.runLocked(() -> _map.get(name)); + try (AutoLock l = _lock.lock()) + { + return _map.get(name); + } } @Override public Enumeration getAttributeNames() { - return _lock.runLocked(() -> Collections.enumeration(getAttributeNameSet())); + try (AutoLock l = _lock.lock()) + { + return Collections.enumeration(_map.keySet()); + } } @Override public Set getAttributeNameSet() { - return _lock.runLocked(_map::keySet); + try (AutoLock l = _lock.lock()) + { + return _map.keySet(); + } } @Override public void clearAttributes() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _map.clear(); this.removeBeans(); diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarFileResource.java b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarFileResource.java index c18494668207..eac18aaf69da 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarFileResource.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarFileResource.java @@ -55,7 +55,7 @@ protected JarFileResource(URL url, boolean useCaches) @Override public void close() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _exists = false; _list = null; @@ -87,7 +87,7 @@ public void close() @Override protected boolean checkConnection() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { try { @@ -110,7 +110,7 @@ protected boolean checkConnection() @Override protected void newConnection() throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { super.newConnection(); @@ -265,7 +265,7 @@ public long lastModified() @Override public String[] list() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (isDirectory() && _list == null) { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java index 276df113b374..9f1d26d03c1f 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/JarResource.java @@ -57,7 +57,7 @@ protected JarResource(URL url, boolean useCaches) @Override public void close() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _jarConnection = null; super.close(); @@ -67,7 +67,7 @@ public void close() @Override protected boolean checkConnection() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { super.checkConnection(); try diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/URLResource.java b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/URLResource.java index 203ab064b8a9..93ab4fa2ffcd 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/resource/URLResource.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/resource/URLResource.java @@ -62,7 +62,7 @@ protected URLResource(URL url, URLConnection connection, boolean useCaches) protected boolean checkConnection() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_connection == null) { @@ -86,7 +86,7 @@ protected boolean checkConnection() @Override public void close() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_in != null) { @@ -114,7 +114,7 @@ public boolean exists() { try { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (checkConnection() && _in == null) _in = _connection.getInputStream(); @@ -219,7 +219,7 @@ public InputStream getInputStream() throws IOException */ protected InputStream getInputStream(boolean resetConnection) throws IOException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (!checkConnection()) throw new IOException("Invalid resource"); diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/security/Credential.java b/jetty-util/src/main/java/org/eclipse/jetty/util/security/Credential.java index 03bac4d9d133..e73531890b78 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/security/Credential.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/security/Credential.java @@ -27,6 +27,7 @@ import java.util.stream.Stream; import org.eclipse.jetty.util.TypeUtil; +import org.eclipse.jetty.util.thread.AutoLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -185,6 +186,8 @@ public static class MD5 extends Credential { private static final long serialVersionUID = 5533846540822684240L; private static final String __TYPE = "MD5:"; + private static final AutoLock __md5Lock = new AutoLock(); + private static MessageDigest __md; private final byte[] _digest; @@ -208,8 +211,15 @@ public boolean check(Object credentials) credentials = new String((char[])credentials); if (credentials instanceof Password || credentials instanceof String) { - MessageDigest md5 = MessageDigest.getInstance("MD5"); - byte[] digest = md5.digest(credentials.toString().getBytes(StandardCharsets.ISO_8859_1)); + byte[] digest; + try (AutoLock l = __md5Lock.lock()) + { + if (__md == null) + __md = MessageDigest.getInstance("MD5"); + __md.reset(); + __md.update(credentials.toString().getBytes(StandardCharsets.ISO_8859_1)); + digest = __md.digest(); + } return byteEquals(_digest, digest); } else if (credentials instanceof MD5) @@ -247,8 +257,27 @@ public static String digest(String password) { try { - MessageDigest md5 = MessageDigest.getInstance("MD5"); - byte[] digest = md5.digest(password.getBytes(StandardCharsets.ISO_8859_1)); + byte[] digest; + try (AutoLock l = __md5Lock.lock()) + { + if (__md == null) + { + try + { + __md = MessageDigest.getInstance("MD5"); + } + catch (Exception e) + { + LOG.warn("Unable to access MD5 message digest", e); + return null; + } + } + + __md.reset(); + __md.update(password.getBytes(StandardCharsets.ISO_8859_1)); + digest = __md.digest(); + } + return __TYPE + TypeUtil.toString(digest, 16); } catch (Exception e) diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/ssl/SslContextFactory.java b/jetty-util/src/main/java/org/eclipse/jetty/util/ssl/SslContextFactory.java index 45e54a865a5c..184ceb25f3bf 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/ssl/SslContextFactory.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/ssl/SslContextFactory.java @@ -214,7 +214,7 @@ public SslContextFactory(boolean trustAll) protected void doStart() throws Exception { super.doStart(); - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { load(); } @@ -438,7 +438,7 @@ List selectionDump() throws NoSuchAlgorithmException @Override protected void doStop() throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { unload(); } @@ -1041,7 +1041,7 @@ public SSLContext getSslContext() if (!isStarted()) return _setContext; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_factory == null) throw new IllegalStateException("SslContextFactory reload failed"); @@ -1422,7 +1422,7 @@ public KeyStore getKeyStore() if (!isStarted()) return _setKeyStore; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_factory == null) throw new IllegalStateException("SslContextFactory reload failed"); @@ -1445,7 +1445,7 @@ public KeyStore getTrustStore() if (!isStarted()) return _setTrustStore; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_factory == null) throw new IllegalStateException("SslContextFactory reload failed"); @@ -1882,7 +1882,7 @@ public SSLParameters customize(SSLParameters sslParams) public void reload(Consumer consumer) throws Exception { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { consumer.accept(this); unload(); diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/statistic/RateStatistic.java b/jetty-util/src/main/java/org/eclipse/jetty/util/statistic/RateStatistic.java index 784be2055287..5f28416fc339 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/statistic/RateStatistic.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/statistic/RateStatistic.java @@ -64,7 +64,7 @@ public TimeUnit getUnits() */ public void reset() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _samples.clear(); _max = 0; @@ -91,7 +91,7 @@ private void update(long now) protected void age(long period, TimeUnit units) { long increment = TimeUnit.NANOSECONDS.convert(period, units); - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { int size = _samples.size(); for (int i = 0; i < size; i++) @@ -110,7 +110,7 @@ protected void age(long period, TimeUnit units) public int record() { long now = System.nanoTime(); - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _count++; _samples.add(now); @@ -127,7 +127,7 @@ public int record() */ public int getRate() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { update(); return _samples.size(); @@ -139,7 +139,10 @@ public int getRate() */ public long getMax() { - return _lock.runLocked(() -> _max); + try (AutoLock l = _lock.lock()) + { + return _max; + } } /** @@ -148,7 +151,7 @@ public long getMax() */ public long getOldest(TimeUnit units) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { Long head = _samples.peekFirst(); if (head == null) @@ -162,7 +165,10 @@ public long getOldest(TimeUnit units) */ public long getCount() { - return _lock.runLocked(() -> _count); + try (AutoLock l = _lock.lock()) + { + return _count; + } } public String dump() @@ -173,7 +179,7 @@ public String dump() public String dump(TimeUnit units) { long now = System.nanoTime(); - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { String samples = _samples.stream() .mapToLong(t -> units.convert(now - t, TimeUnit.NANOSECONDS)) @@ -191,7 +197,7 @@ public String toString() private String toString(long nanoTime) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { update(nanoTime); return String.format("%s@%x{count=%d,max=%d,rate=%d per %d %s}", diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/AutoLock.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/AutoLock.java index bac7edbf626e..b956d8cb0702 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/AutoLock.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/AutoLock.java @@ -22,7 +22,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Supplier; /** *

Reentrant lock that can be used in a try-with-resources statement.

@@ -36,6 +35,8 @@ */ public class AutoLock implements AutoCloseable, Serializable { + private static final long serialVersionUID = 3300696774541816341L; + private final ReentrantLock _lock = new ReentrantLock(); /** @@ -49,48 +50,6 @@ public AutoLock lock() return this; } - /** - *

Runs the given code with the lock held.

- *

This is equivalent to:

- *
-     * try (AutoLock ignored = lock())
-     * {
-     *     code.run();
-     * }
-     * 
- * - * @param code the code to run with the lock held. - */ - public void runLocked(Runnable code) - { - try (AutoLock ignored = lock()) - { - code.run(); - } - } - - /** - *

Returns the result of running the given code with the lock held.

- *

This is equivalent to:

- *
-     * try (AutoLock ignored = lock())
-     * {
-     *     return code.get();
-     * }
-     * 
- * - * @param code the code to run with the lock held. - * @param the result type - * @return the result of the code run - */ - public T runLocked(Supplier code) - { - try (AutoLock ignored = lock()) - { - return code.get(); - } - } - /** * @see ReentrantLock#isHeldByCurrentThread() * @return whether this lock is held by the current thread diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java index 6accd65fe3b8..6022858ab400 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/QueuedThreadPool.java @@ -277,9 +277,9 @@ else if (job != NOOP) if (_budget != null) _budget.reset(); - try (AutoLock.WithCondition lock = _joinLock.lock()) + try (AutoLock.WithCondition l = _joinLock.lock()) { - lock.signalAll(); + l.signalAll(); } } @@ -570,11 +570,11 @@ public boolean tryExecute(Runnable task) @Override public void join() throws InterruptedException { - try (AutoLock.WithCondition lock = _joinLock.lock()) + try (AutoLock.WithCondition l = _joinLock.lock()) { while (isRunning()) { - lock.await(); + l.await(); } } diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java index be74c189ba33..282963285474 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java @@ -18,7 +18,6 @@ package org.eclipse.jetty.util.thread; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -37,11 +36,11 @@ public class ShutdownThread extends Thread { private static final Logger LOG = LoggerFactory.getLogger(ShutdownThread.class); - private static final ShutdownThread INSTANCE = new ShutdownThread(); + private static final ShutdownThread _thread = new ShutdownThread(); private final AutoLock _lock = new AutoLock(); - private final List _lifeCycles = new CopyOnWriteArrayList<>(); private boolean _hooked; + private final List _lifeCycles = new CopyOnWriteArrayList(); /** * Default constructor for the singleton @@ -55,7 +54,7 @@ private ShutdownThread() private void hook() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (!_hooked) Runtime.getRuntime().addShutdownHook(this); @@ -70,7 +69,7 @@ private void hook() private void unhook() { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _hooked = false; Runtime.getRuntime().removeShutdownHook(this); @@ -83,53 +82,57 @@ private void unhook() } /** - * @return the singleton instance of the ShutdownThread + * Returns the instance of the singleton + * + * @return the singleton instance of the {@link ShutdownThread} */ public static ShutdownThread getInstance() { - return INSTANCE; + return _thread; } public static void register(LifeCycle... lifeCycles) { - try (AutoLock ignored = INSTANCE._lock.lock()) + try (AutoLock l = _thread._lock.lock()) { - INSTANCE._lifeCycles.addAll(Arrays.asList(lifeCycles)); - if (INSTANCE._lifeCycles.size() > 0) - INSTANCE.hook(); + _thread._lifeCycles.addAll(Arrays.asList(lifeCycles)); + if (_thread._lifeCycles.size() > 0) + _thread.hook(); } } public static void register(int index, LifeCycle... lifeCycles) { - try (AutoLock ignored = INSTANCE._lock.lock()) + try (AutoLock l = _thread._lock.lock()) { - INSTANCE._lifeCycles.addAll(index, Arrays.asList(lifeCycles)); - if (INSTANCE._lifeCycles.size() > 0) - INSTANCE.hook(); + _thread._lifeCycles.addAll(index, Arrays.asList(lifeCycles)); + if (_thread._lifeCycles.size() > 0) + _thread.hook(); } } public static void deregister(LifeCycle lifeCycle) { - try (AutoLock ignored = INSTANCE._lock.lock()) + try (AutoLock l = _thread._lock.lock()) { - INSTANCE._lifeCycles.remove(lifeCycle); - if (INSTANCE._lifeCycles.size() == 0) - INSTANCE.unhook(); + _thread._lifeCycles.remove(lifeCycle); + if (_thread._lifeCycles.size() == 0) + _thread.unhook(); } } public static boolean isRegistered(LifeCycle lifeCycle) { - return INSTANCE._lock.runLocked(() -> INSTANCE._lifeCycles.contains(lifeCycle)); + try (AutoLock l = _thread._lock.lock()) + { + return _thread._lifeCycles.contains(lifeCycle); + } } @Override public void run() { - List lifeCycles = INSTANCE._lock.runLocked(() -> new ArrayList<>(INSTANCE._lifeCycles)); - for (LifeCycle lifeCycle : lifeCycles) + for (LifeCycle lifeCycle : _thread._lifeCycles) { try { diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/strategy/EatWhatYouKill.java b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/strategy/EatWhatYouKill.java index 5b2cb557246c..c80f57dbfe9a 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/thread/strategy/EatWhatYouKill.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/thread/strategy/EatWhatYouKill.java @@ -99,7 +99,7 @@ public EatWhatYouKill(Producer producer, Executor executor) public void dispatch() { boolean execute = false; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { switch (_state) { @@ -142,7 +142,7 @@ private void tryProduce(boolean wasPending) if (LOG.isDebugEnabled()) LOG.debug("{} tryProduce {}", this, wasPending); - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (wasPending) _pending = false; @@ -187,7 +187,7 @@ private boolean doProduce(boolean nonBlocking) if (task == null) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // Could another task just have been queued with a produce call? switch (_state) @@ -239,7 +239,7 @@ private boolean doProduce(boolean nonBlocking) case BLOCKING: // The task is blocking, so PC is not an option. Thus we choose // between EPC and PEC based on the availability of a reserved thread. - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_pending) { @@ -262,7 +262,7 @@ else if (_tryExecutor.tryExecute(this)) case EITHER: // The task may be non blocking, so PC is an option. Thus we choose // between EPC and PC based on the availability of a reserved thread. - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_pending) { @@ -315,7 +315,7 @@ else if (_tryExecutor.tryExecute(this)) runTask(task); // Try to produce again? - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_state == State.IDLE) { @@ -422,7 +422,10 @@ public long getEPCTasksConsumed() @ManagedAttribute(value = "whether this execution strategy is idle", readonly = true) public boolean isIdle() { - return _lock.runLocked(() -> _state == State.IDLE); + try (AutoLock l = _lock.lock()) + { + return _state == State.IDLE; + } } @ManagedOperation(value = "resets the task counts", impact = "ACTION") @@ -437,7 +440,10 @@ public void reset() @Override public String toString() { - return _lock.runLocked(this::toStringLocked); + try (AutoLock l = _lock.lock()) + { + return toStringLocked(); + } } public String toStringLocked() diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java index aaf98302a394..8524a36098f2 100644 --- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java +++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/Configurations.java @@ -74,49 +74,47 @@ public class Configurations extends AbstractList implements Dumpa public static List getKnown() { - try (AutoLock ignored = __lock.lock()) + try (AutoLock l = __lock.lock()) { - if (!__known.isEmpty()) - return __known; - - TypeUtil.serviceProviderStream(ServiceLoader.load(Configuration.class)).forEach(provider -> + if (__known.isEmpty()) { - try + TypeUtil.serviceProviderStream(ServiceLoader.load(Configuration.class)).forEach(provider -> { - Configuration configuration = provider.get(); - if (!configuration.isAvailable()) + try { - if (LOG.isDebugEnabled()) - LOG.debug("Configuration unavailable: " + configuration); - __unavailable.add(configuration); - return; + Configuration configuration = provider.get(); + if (!configuration.isAvailable()) + { + if (LOG.isDebugEnabled()) + LOG.debug("Configuration unavailable: " + configuration); + __unavailable.add(configuration); + return; + } + __known.add(configuration); + __knownByClassName.add(configuration.getClass().getName()); } - __known.add(configuration); - __knownByClassName.add(configuration.getClass().getName()); - } - catch (Throwable e) - { - LOG.warn("Unable to get known Configuration", e); - } - }); - sort(__known); - if (LOG.isDebugEnabled()) - { - for (Configuration c : __known) + catch (Throwable e) + { + LOG.warn("Unable to get known Configuration", e); + } + }); + sort(__known); + if (LOG.isDebugEnabled()) { - LOG.debug("known {}", c); + for (Configuration c : __known) + { + LOG.debug("known {}", c); + } + LOG.debug("Known Configurations {}", __knownByClassName); } } - - if (LOG.isDebugEnabled()) - LOG.debug("Known Configurations {}", __knownByClassName); return __known; } } public static void setKnown(String... classes) { - try (AutoLock ignored = __lock.lock()) + try (AutoLock l = __lock.lock()) { if (!__known.isEmpty()) throw new IllegalStateException("Known configuration classes already set"); @@ -149,17 +147,15 @@ public static void setKnown(String... classes) { LOG.debug("known {}", c); } - } - - if (LOG.isDebugEnabled()) LOG.debug("Known Configurations {}", __knownByClassName); + } } } // Only used by tests. - static void clearKnown() + static void cleanKnown() { - try (AutoLock ignored = __lock.lock()) + try (AutoLock l = __lock.lock()) { __known.clear(); __unavailable.clear(); diff --git a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java index b778e6657184..65645e1bdd86 100644 --- a/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java +++ b/jetty-webapp/src/main/java/org/eclipse/jetty/webapp/MetaData.java @@ -367,7 +367,7 @@ public void addDiscoveredAnnotation(DiscoveredAnnotation annotation) if (annotation == null) return; - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { //if no resource associated with an annotation map it to empty resource - these //annotations will always be processed first diff --git a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/ConfigurationsTest.java b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/ConfigurationsTest.java index c0c4622969b8..02c8632211e3 100644 --- a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/ConfigurationsTest.java +++ b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/ConfigurationsTest.java @@ -34,13 +34,13 @@ public class ConfigurationsTest @AfterEach public void tearDown() { - Configurations.clearKnown(); + Configurations.cleanKnown(); } @BeforeEach public void setup() { - Configurations.clearKnown(); + Configurations.cleanKnown(); } @Test diff --git a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java index 481923fa079f..17c9fc6336cc 100644 --- a/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java +++ b/jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java @@ -76,7 +76,7 @@ public void sessionDestroyed(HttpSessionEvent se) @AfterEach public void tearDown() { - Configurations.clearKnown(); + Configurations.cleanKnown(); } @Test @@ -157,7 +157,7 @@ public void testSessionListeners() @Test public void testConfigurationClassesFromDefault() { - Configurations.clearKnown(); + Configurations.cleanKnown(); String[] knownAndEnabled = Configurations.getKnown().stream() .filter(c -> c.isEnabledByDefault()) .map(c -> c.getClass().getName()) @@ -182,7 +182,7 @@ public void testConfigurationClassesFromDefault() @Test public void testConfigurationOrder() { - Configurations.clearKnown(); + Configurations.cleanKnown(); WebAppContext wac = new WebAppContext(); wac.setServer(new Server()); assertThat(wac.getConfigurations().stream().map(c -> c.getClass().getName()).collect(Collectors.toList()), @@ -199,7 +199,7 @@ public void testConfigurationOrder() @Test public void testConfigurationInstances() { - Configurations.clearKnown(); + Configurations.cleanKnown(); Configuration[] configs = {new WebInfConfiguration()}; WebAppContext wac = new WebAppContext(); wac.setConfigurations(configs); diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameFlusher.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameFlusher.java index f763c961cd29..c1ea4585efc2 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameFlusher.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameFlusher.java @@ -116,7 +116,7 @@ public boolean enqueue(Frame frame, Callback callback, boolean batch) List failedEntries = null; CloseStatus closeStatus = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (canEnqueue) { @@ -188,7 +188,10 @@ public boolean enqueue(Frame frame, Callback callback, boolean batch) public void onClose(Throwable cause) { - lock.runLocked(() -> closedCause = cause == null ? CLOSED_CHANNEL : cause); + try (AutoLock l = lock.lock()) + { + closedCause = cause == null ? CLOSED_CHANNEL : cause; + } iterate(); } @@ -200,7 +203,7 @@ protected Action process() throws Throwable boolean flush = false; Callback releasingCallback = this; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (closedCause != null) throw closedCause; @@ -347,13 +350,16 @@ private ByteBuffer acquireBuffer(int capacity) private int getQueueSize() { - return lock.runLocked(queue::size); + try (AutoLock l = lock.lock()) + { + return queue.size(); + } } public void timeoutExpired() { boolean failed = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (closedCause != null) return; @@ -404,7 +410,7 @@ public void onCompleteFailure(Throwable failure) { BufferUtil.clear(batchBuffer); releaseAggregate(); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { failedEntries.addAll(queue); queue.clear(); diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameSequence.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameSequence.java index c2d1ba278e8e..f37f7e8b929d 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameSequence.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/FrameSequence.java @@ -30,7 +30,7 @@ public class FrameSequence public void check(byte opcode, boolean fin) throws ProtocolException { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (state == OpCode.CLOSE) throw new ProtocolException(OpCode.name(opcode) + " after CLOSE"); diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/TransformingFlusher.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/TransformingFlusher.java index b73166ab2ce0..1bcfe4a73292 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/TransformingFlusher.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/TransformingFlusher.java @@ -70,7 +70,7 @@ public final void sendFrame(Frame frame, Callback callback, boolean batch) log.debug("Queuing {}", entry); boolean enqueued = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (failure == null) enqueued = entries.add(entry); @@ -84,7 +84,7 @@ public final void sendFrame(Frame frame, Callback callback, boolean batch) private void onFailure(Throwable t) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (failure == null) failure = t; @@ -97,7 +97,10 @@ private void onFailure(Throwable t) private FrameEntry pollEntry() { - return lock.runLocked(entries::poll); + try (AutoLock l = lock.lock()) + { + return entries.poll(); + } } private class Flusher extends IteratingCallback implements Callback diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketConnection.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketConnection.java index d13f6626b317..c34e86c4e80b 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketConnection.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketConnection.java @@ -264,7 +264,7 @@ public void failed(Throwable cause) private void acquireNetworkBuffer() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (networkBuffer == null) networkBuffer = newNetworkBuffer(getInputBufferSize()); @@ -273,7 +273,7 @@ private void acquireNetworkBuffer() private void reacquireNetworkBuffer() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (networkBuffer == null) throw new IllegalStateException(); @@ -293,7 +293,7 @@ private RetainableByteBuffer newNetworkBuffer(int capacity) private void releaseNetworkBuffer() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (networkBuffer == null) throw new IllegalStateException(); @@ -328,7 +328,7 @@ public void demand(long n) throw new IllegalArgumentException("Demand must be positive"); boolean fillAndParse = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("demand {} d={} fp={} {} {}", n, demand, fillingAndParsing, networkBuffer, this); @@ -361,7 +361,7 @@ public void demand(long n) public boolean moreDemand() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("moreDemand? d={} fp={} {} {}", demand, fillingAndParsing, networkBuffer, this); @@ -381,7 +381,7 @@ public boolean moreDemand() public boolean meetDemand() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("meetDemand d={} fp={} {} {}", demand, fillingAndParsing, networkBuffer, this); @@ -400,7 +400,7 @@ public boolean meetDemand() public void cancelDemand() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (LOG.isDebugEnabled()) LOG.debug("cancelDemand d={} fp={} {} {}", demand, fillingAndParsing, networkBuffer, this); @@ -487,7 +487,10 @@ protected void setInitialBuffer(ByteBuffer initialBuffer) { if (LOG.isDebugEnabled()) LOG.debug("Set initial buffer - {}", BufferUtil.toDetailString(initialBuffer)); - lock.runLocked(() -> networkBuffer = newNetworkBuffer(initialBuffer.remaining())); + try (AutoLock l = lock.lock()) + { + networkBuffer = newNetworkBuffer(initialBuffer.remaining()); + } ByteBuffer buffer = networkBuffer.getBuffer(); BufferUtil.clearToFill(buffer); BufferUtil.put(initialBuffer, buffer); diff --git a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketSessionState.java b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketSessionState.java index a2926af60fee..9f1be535c484 100644 --- a/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketSessionState.java +++ b/jetty-websocket/websocket-core-common/src/main/java/org/eclipse/jetty/websocket/core/internal/WebSocketSessionState.java @@ -50,7 +50,7 @@ enum State public void onConnected() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (_sessionState != State.CONNECTING) throw new IllegalStateException(_sessionState.toString()); @@ -61,7 +61,7 @@ public void onConnected() public void onOpen() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { switch (_sessionState) { @@ -82,7 +82,10 @@ public void onOpen() private State getState() { - return lock.runLocked(() -> _sessionState); + try (AutoLock l = lock.lock()) + { + return _sessionState; + } } public boolean isClosed() @@ -104,12 +107,15 @@ public boolean isOutputOpen() public CloseStatus getCloseStatus() { - return lock.runLocked(() -> _closeStatus); + try (AutoLock l = lock.lock()) + { + return _closeStatus; + } } public boolean onClosed(CloseStatus closeStatus) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (_sessionState == State.CLOSED) return false; @@ -138,7 +144,7 @@ public boolean onClosed(CloseStatus closeStatus) */ public void onError(Throwable t) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (_sessionState != State.CLOSED || _closeStatus == null) throw new IllegalArgumentException(); @@ -155,7 +161,7 @@ public void onError(Throwable t) public boolean onEof() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { switch (_sessionState) { @@ -177,7 +183,7 @@ public boolean onOutgoingFrame(Frame frame) throws Exception byte opcode = frame.getOpCode(); boolean fin = frame.isFin(); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (!isOutputOpen()) throw new ClosedChannelException(); @@ -220,7 +226,7 @@ public boolean onIncomingFrame(Frame frame) throws ProtocolException byte opcode = frame.getOpCode(); boolean fin = frame.isFin(); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (!isInputOpen()) throw new IllegalStateException(_sessionState.toString()); diff --git a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java index d1a9aa5c093d..72e09f858a2d 100644 --- a/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java +++ b/jetty-websocket/websocket-javax-common/src/main/java/org/eclipse/jetty/websocket/javax/common/JavaxWebSocketFrameHandler.java @@ -62,11 +62,38 @@ public class JavaxWebSocketFrameHandler implements FrameHandler { private final AutoLock lock = new AutoLock(); - private final AtomicBoolean closeNotified = new AtomicBoolean(); - private final Map messageHandlerMap = new HashMap<>(); private final Logger logger; private final JavaxWebSocketContainer container; private final Object endpointInstance; + private final AtomicBoolean closeNotified = new AtomicBoolean(); + + /** + * List of configured named variables in the uri-template. + *

+ * Used to bind uri-template variables, with their values from the upgrade, to the methods + * that have declared their interest in these values via {@code @PathParam} annotations. + *

+ *

+ * Can be null if client side, or no named variables were configured on the server side. + *

+ */ + /** + * The Map of path parameter values that arrived during the server side upgrade process. + *

+ * Used to bind uri-template variables, with their values from the upgrade, to the methods + * that have declared their interest in these values via {@code @PathParam} annotations. + *

+ *

+ * The values are represented as {@link String} and are essentially static for this + * instance of the the JavaxWebSocketFrameHandler. They will be converted to the + * type declared by the {@code @PathParam} annotations following the JSR356 advice + * to only support String, Java Primitives (or their Boxed version). + *

+ *

+ * Can be null if client side, or no named variables were configured on the server side, + * or the server side component didn't use the {@link org.eclipse.jetty.http.pathmap.UriTemplatePathSpec} for its mapping. + *

+ */ private MethodHandle openHandle; private MethodHandle closeHandle; private MethodHandle errorHandle; @@ -75,6 +102,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler private JavaxWebSocketMessageMetadata binaryMetadata; private UpgradeRequest upgradeRequest; private EndpointConfig endpointConfig; + private final Map messageHandlerMap = new HashMap<>(); private MessageSink textSink; private MessageSink binarySink; private MessageSink activeMessageSink; @@ -497,7 +525,7 @@ private void registerMessageHandler(Class clazz, MessageHandler handler, byte private MessageSink registerMessageHandler(byte basicWebSocketMessageType, Class handlerType, MessageHandler handler, MessageSink messageSink) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { RegisteredMessageHandler registeredHandler = messageHandlerMap.get(basicWebSocketMessageType); if (registeredHandler != null) @@ -517,7 +545,7 @@ private MessageSink registerMessageHandler(byte basicWebSocketMessageType, C public void removeMessageHandler(MessageHandler handler) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { Optional> optionalEntry = messageHandlerMap.entrySet().stream() .filter((entry) -> entry.getValue().getMessageHandler().equals(handler)) diff --git a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java index ae0d26754055..fefc6a32c1d5 100644 --- a/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java +++ b/jetty-websocket/websocket-jetty-common/src/main/java/org/eclipse/jetty/websocket/common/JettyWebSocketFrameHandler.java @@ -191,7 +191,7 @@ public void onOpen(CoreSession coreSession, Callback callback) @Override public void onFrame(Frame frame, Callback callback) { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { switch (state) { @@ -300,8 +300,11 @@ private void onCloseFrame(Frame frame, Callback callback) @Override public void onClosed(CloseStatus closeStatus, Callback callback) { - // We are now closed and cannot suspend or resume. - lock.runLocked(() -> state = SuspendState.CLOSED); + try (AutoLock l = lock.lock()) + { + // We are now closed and cannot suspend or resume. + state = SuspendState.CLOSED; + } notifyOnClose(closeStatus, callback); container.notifySessionListeners((listener) -> listener.onWebSocketSessionClosed(session)); @@ -424,7 +427,7 @@ public boolean isDemanding() public void suspend() { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { switch (state) { @@ -442,7 +445,7 @@ public void resume() { boolean needDemand = false; Runnable delayedFrame = null; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { switch (state) { @@ -479,7 +482,7 @@ public void resume() private void demand() { boolean demand = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { switch (state) { diff --git a/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java index f92295a0cef4..c3bc69867695 100644 --- a/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageInputStream.java @@ -59,7 +59,7 @@ public void accept(Frame frame, Callback callback) LOG.debug("accepting {}", frame); boolean succeed = false; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { // If closed or we have no payload, request the next frame. if (closed || (!frame.hasPayload() && !frame.isFin())) @@ -137,7 +137,7 @@ public void close() throws IOException LOG.debug("close()"); ArrayList entries = new ArrayList<>(); - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (closed) return; @@ -172,7 +172,7 @@ public void setTimeout(long timeoutMs) private void succeedCurrentEntry() { Entry current; - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { current = currentEntry; currentEntry = null; @@ -183,7 +183,7 @@ private void succeedCurrentEntry() private Entry getCurrentEntry() throws IOException { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (currentEntry != null) return currentEntry; @@ -208,7 +208,7 @@ private Entry getCurrentEntry() throws IOException throw new IOException(String.format("Read timeout: %,dms expired", timeoutMs)); } - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { currentEntry = result; return currentEntry; diff --git a/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java index ab7087d4b464..e3b841bc05e3 100644 --- a/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java +++ b/jetty-websocket/websocket-util/src/main/java/org/eclipse/jetty/websocket/util/messages/MessageOutputStream.java @@ -125,7 +125,7 @@ public void flush() throws IOException private void flush(boolean fin) throws IOException { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (closed) throw new IOException("Stream is closed"); @@ -159,7 +159,7 @@ private void flush(boolean fin) throws IOException private void send(ByteBuffer data) throws IOException { - try (AutoLock ignored = lock.lock()) + try (AutoLock l = lock.lock()) { if (closed) throw new IOException("Stream is closed"); @@ -199,19 +199,30 @@ public void close() throws IOException public void setCallback(Callback callback) { - lock.runLocked(() -> this.callback = callback); + try (AutoLock l = lock.lock()) + { + this.callback = callback; + } } private void notifySuccess() { - Callback callback = lock.runLocked(() -> this.callback); + Callback callback; + try (AutoLock l = lock.lock()) + { + callback = this.callback; + } if (callback != null) callback.succeeded(); } private void notifyFailure(Throwable failure) { - Callback callback = lock.runLocked(() -> this.callback); + Callback callback; + try (AutoLock l = lock.lock()) + { + callback = this.callback; + } if (callback != null) callback.failed(failure); } diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java index d11bb162b494..199fc034f8eb 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java @@ -250,7 +250,7 @@ public static String normalizeURI(String uri) */ public XmlConfiguration(Resource resource) throws SAXException, IOException { - try (AutoLock ignored = PARSER.lock()) + try (AutoLock l = PARSER.lock()) { _location = resource; try (InputStream inputStream = resource.getInputStream()) diff --git a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlParser.java b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlParser.java index 007ab207b9cd..28f143861de9 100644 --- a/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlParser.java +++ b/jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlParser.java @@ -58,14 +58,17 @@ public class XmlParser private static final Logger LOG = LoggerFactory.getLogger(XmlParser.class); private final AutoLock _lock = new AutoLock(); - private final Map _redirectMap = new HashMap<>(); - private final Stack _observers = new Stack<>(); + private Map _redirectMap = new HashMap(); private SAXParser _parser; private Map _observerMap; + private Stack _observers = new Stack(); private String _xpath; private Object _xpaths; private String _dtd; + /** + * Construct + */ public XmlParser() { SAXParserFactory factory = SAXParserFactory.newInstance(); @@ -134,7 +137,12 @@ public boolean isValidating() public void redirectEntity(String name, URL entity) { if (entity != null) - _lock.runLocked(() -> _redirectMap.put(name, entity)); + { + try (AutoLock l = _lock.lock()) + { + _redirectMap.put(name, entity); + } + } } /** @@ -176,7 +184,7 @@ public String getDTD() */ public void addContentHandler(String trigger, ContentHandler observer) { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { if (_observerMap == null) _observerMap = new HashMap<>(); @@ -186,7 +194,7 @@ public void addContentHandler(String trigger, ContentHandler observer) public Node parse(InputSource source) throws IOException, SAXException { - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { _dtd = null; Handler handler = new Handler(); @@ -628,7 +636,7 @@ public Node get(String tag) public void add(int i, Object o) { if (_list == null) - _list = new ArrayList<>(); + _list = new ArrayList(); if (o instanceof String) { if (_lastString) diff --git a/tests/jetty-http-tools/src/test/java/org/eclipse/jetty/http/tools/HttpTesterTest.java b/tests/jetty-http-tools/src/test/java/org/eclipse/jetty/http/tools/HttpTesterTest.java index 0fce50844f89..c09db1f64977 100644 --- a/tests/jetty-http-tools/src/test/java/org/eclipse/jetty/http/tools/HttpTesterTest.java +++ b/tests/jetty-http-tools/src/test/java/org/eclipse/jetty/http/tools/HttpTesterTest.java @@ -256,7 +256,7 @@ public void testResponsesSplitInput() throws Exception PipedInputStream stream = new PipedInputStream(src) { @Override - public int read(byte[] b, int off, int len) throws IOException + public synchronized int read(byte[] b, int off, int len) throws IOException { if (available() == 0) return 0; diff --git a/tests/jetty-jmh/src/main/java/org/eclipse/jetty/util/jmh/DateCacheSimpleDateFormat.java b/tests/jetty-jmh/src/main/java/org/eclipse/jetty/util/jmh/DateCacheSimpleDateFormat.java index 10430a84d801..46215aca691f 100644 --- a/tests/jetty-jmh/src/main/java/org/eclipse/jetty/util/jmh/DateCacheSimpleDateFormat.java +++ b/tests/jetty-jmh/src/main/java/org/eclipse/jetty/util/jmh/DateCacheSimpleDateFormat.java @@ -46,7 +46,9 @@ public class DateCacheSimpleDateFormat private final AutoLock _lock = new AutoLock(); private final String _formatString; + private final String _tzFormatString; private final SimpleDateFormat _tzFormat; + private final Locale _locale; private volatile Tick _tick; public static class Tick @@ -95,9 +97,9 @@ public DateCacheSimpleDateFormat(String format, Locale l, String tz) public DateCacheSimpleDateFormat(String format, Locale l, TimeZone tz) { _formatString = format; + _locale = l; int zIndex = _formatString.indexOf("ZZZ"); - String tzFormatString; if (zIndex >= 0) { final String ss1 = _formatString.substring(0, zIndex); @@ -128,17 +130,21 @@ public DateCacheSimpleDateFormat(String format, Locale l, TimeZone tz) sb.append('\''); sb.append(ss2); - tzFormatString = sb.toString(); + _tzFormatString = sb.toString(); } else { - tzFormatString = _formatString; + _tzFormatString = _formatString; } - if (l != null) - _tzFormat = new SimpleDateFormat(tzFormatString, l); + if (_locale != null) + { + _tzFormat = new SimpleDateFormat(_tzFormatString, _locale); + } else - _tzFormat = new SimpleDateFormat(tzFormatString); + { + _tzFormat = new SimpleDateFormat(_tzFormatString); + } _tzFormat.setTimeZone(tz); _tick = null; @@ -165,7 +171,10 @@ public String format(Date inDate) if (tick == null || seconds != tick._seconds) { // It's a cache miss - return _lock.runLocked(() -> _tzFormat.format(inDate)); + try (AutoLock l = _lock.lock()) + { + return _tzFormat.format(inDate); + } } return tick._string; @@ -190,7 +199,10 @@ public String format(long inDate) { // It's a cache miss Date d = new Date(inDate); - return _lock.runLocked(() -> _tzFormat.format(d)); + try (AutoLock l = _lock.lock()) + { + return _tzFormat.format(d); + } } return tick._string; @@ -232,7 +244,7 @@ protected Tick formatTick(long now) long seconds = now / 1000; // Synchronize to protect _tzFormat - try (AutoLock ignored = _lock.lock()) + try (AutoLock l = _lock.lock()) { // recheck the tick, to save multiple formats if (_tick == null || _tick._seconds != seconds) From edd6ca2ee1d70b3e5cc578103b8371c04f14f7b6 Mon Sep 17 00:00:00 2001 From: Simone Bordet Date: Tue, 4 Aug 2020 15:43:39 +0200 Subject: [PATCH 3/3] Issue #5083 - Convert synchronized usages to AutoLock. Updates after review. Signed-off-by: Simone Bordet --- .../jetty/util/RolloverFileOutputStream.java | 59 +++++++++---------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java b/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java index ba150d0c11e8..f4ef64a25ac6 100644 --- a/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java +++ b/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java @@ -29,8 +29,10 @@ import java.util.Date; import java.util.Locale; import java.util.TimeZone; -import java.util.Timer; -import java.util.TimerTask; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; import org.eclipse.jetty.util.thread.AutoLock; @@ -48,22 +50,26 @@ */ public class RolloverFileOutputStream extends OutputStream { - private static Timer __rollover; - static final String YYYY_MM_DD = "yyyy_mm_dd"; static final String ROLLOVER_FILE_DATE_FORMAT = "yyyy_MM_dd"; static final String ROLLOVER_FILE_BACKUP_FORMAT = "HHmmssSSS"; static final int ROLLOVER_FILE_RETAIN_DAYS = 31; + private static final ScheduledExecutorService __scheduler = Executors.newSingleThreadScheduledExecutor(job -> + { + Thread thread = new Thread(job, RolloverFileOutputStream.class.getName()); + thread.setDaemon(true); + return thread; + }); private final AutoLock _lock = new AutoLock(); private OutputStream _out; - private RollTask _rollTask; - private SimpleDateFormat _fileBackupFormat; - private SimpleDateFormat _fileDateFormat; + private ScheduledFuture _rollTask; + private final SimpleDateFormat _fileBackupFormat; + private final SimpleDateFormat _fileDateFormat; private String _filename; private File _file; - private boolean _append; - private int _retainDays; + private final boolean _append; + private final int _retainDays; /** * @param filename The filename must include the string "yyyy_mm_dd", @@ -178,8 +184,6 @@ public RolloverFileOutputStream(String filename, // Calculate Today's Midnight, based on Configured TimeZone (will be in past, even if by a few milliseconds) setFile(now); - __rollover = new Timer(RolloverFileOutputStream.class.getName(), true); - // This will schedule the rollover event to the next midnight scheduleNextRollover(now); } @@ -197,13 +201,12 @@ public static ZonedDateTime toMidnight(ZonedDateTime now) private void scheduleNextRollover(ZonedDateTime now) { - _rollTask = new RollTask(); // Get tomorrow's midnight based on Configured TimeZone ZonedDateTime midnight = toMidnight(now); // Schedule next rollover event to occur, based on local machine's Unix Epoch milliseconds long delay = midnight.toInstant().toEpochMilli() - now.toInstant().toEpochMilli(); - __rollover.schedule(_rollTask, delay); + _rollTask = __scheduler.schedule(this::rollOver, delay, TimeUnit.MILLISECONDS); } public String getFilename() @@ -394,28 +397,24 @@ public void close() throws IOException } } - RollTask rollTask = _rollTask; + ScheduledFuture rollTask = _rollTask; if (rollTask != null) - rollTask.cancel(); + rollTask.cancel(false); } - private class RollTask extends TimerTask + private void rollOver() { - @Override - public void run() + try { - try - { - ZonedDateTime now = ZonedDateTime.now(_fileDateFormat.getTimeZone().toZoneId()); - RolloverFileOutputStream.this.setFile(now); - RolloverFileOutputStream.this.removeOldFiles(now); - RolloverFileOutputStream.this.scheduleNextRollover(now); - } - catch (Throwable t) - { - // Cannot log this exception to a LOG, as RolloverFOS can be used by logging - t.printStackTrace(System.err); - } + ZonedDateTime now = ZonedDateTime.now(_fileDateFormat.getTimeZone().toZoneId()); + RolloverFileOutputStream.this.setFile(now); + RolloverFileOutputStream.this.removeOldFiles(now); + RolloverFileOutputStream.this.scheduleNextRollover(now); + } + catch (Throwable t) + { + // Cannot log this exception to a LOG, as RolloverFOS can be used by logging + t.printStackTrace(System.err); } } }