Fixes #5083 - Convert synchronized usages to AutoLock.

Updates after review.

Signed-off-by: Simone Bordet <simone.bordet@gmail.com>
This commit is contained in:
Simone Bordet 2020-07-29 15:34:01 +02:00
parent 8d69fc41a7
commit 089e51f0bc
86 changed files with 1618 additions and 1168 deletions

View File

@ -198,7 +198,7 @@ public class AnnotationIntrospector
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

View File

@ -60,7 +60,7 @@ public abstract class HttpChannel
{
boolean result = false;
boolean abort = true;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_exchange == null)
{
@ -87,7 +87,7 @@ public abstract class HttpChannel
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 abstract class HttpChannel
public HttpExchange getHttpExchange()
{
return _lock.runLocked(() -> _exchange);
try (AutoLock l = _lock.lock())
{
return _exchange;
}
}
protected abstract HttpSender getHttpSender();

View File

@ -89,7 +89,7 @@ public abstract class HttpConnection implements IConnection
// 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 @@ public abstract class HttpConnection implements IConnection
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 @@ public abstract class HttpConnection implements IConnection
public boolean onIdleTimeout(long idleTimeout)
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (idleTimeoutGuard == 0)
{

View File

@ -70,7 +70,10 @@ public class HttpExchange
public Throwable getRequestFailure()
{
return lock.runLocked(() -> requestFailure);
try (AutoLock l = lock.lock())
{
return requestFailure;
}
}
public List<Response.ResponseListener> getResponseListeners()
@ -85,7 +88,10 @@ public class HttpExchange
public Throwable getResponseFailure()
{
return lock.runLocked(() -> responseFailure);
try (AutoLock l = lock.lock())
{
return responseFailure;
}
}
/**
@ -99,7 +105,7 @@ public class HttpExchange
{
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 @@ public class HttpExchange
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 @@ public class HttpExchange
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 @@ public class HttpExchange
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 @@ public class HttpExchange
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 class HttpExchange
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 class HttpExchange
// 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 @@ public class HttpExchange
public void resetResponse()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
responseState = State.PENDING;
responseFailure = null;
@ -287,7 +302,7 @@ public class HttpExchange
@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(),

View File

@ -100,7 +100,7 @@ public abstract class HttpReceiver
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 @@ public abstract class HttpReceiver
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;

View File

@ -82,13 +82,19 @@ public class MultiplexConnectionPool extends AbstractConnectionPool implements C
@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 class MultiplexConnectionPool extends AbstractConnectionPool implements C
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 class MultiplexConnectionPool extends AbstractConnectionPool implements C
@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 @@ public class MultiplexConnectionPool extends AbstractConnectionPool implements C
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 class MultiplexConnectionPool extends AbstractConnectionPool implements C
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 @@ public class MultiplexConnectionPool extends AbstractConnectionPool implements C
{
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 class MultiplexConnectionPool extends AbstractConnectionPool implements C
{
super.close();
List<Connection> 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 class MultiplexConnectionPool extends AbstractConnectionPool implements C
{
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 class MultiplexConnectionPool extends AbstractConnectionPool implements C
public boolean sweep()
{
List<Connection> 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 class MultiplexConnectionPool extends AbstractConnectionPool implements C
{
int activeSize;
int idleSize;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
activeSize = activeConnections.size();
idleSize = idleConnections.size();

View File

@ -55,13 +55,19 @@ public class RoundRobinConnectionPool extends AbstractConnectionPool implements
@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 class RoundRobinConnectionPool extends AbstractConnectionPool implements
@Override
protected void onCreated(Connection connection)
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
for (Entry entry : entries)
{
@ -100,7 +106,7 @@ public class RoundRobinConnectionPool extends AbstractConnectionPool implements
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 @@ public class RoundRobinConnectionPool extends AbstractConnectionPool implements
@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 class RoundRobinConnectionPool extends AbstractConnectionPool implements
{
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 class RoundRobinConnectionPool extends AbstractConnectionPool implements
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 class RoundRobinConnectionPool extends AbstractConnectionPool implements
@Override
public void dump(Appendable out, String indent) throws IOException
{
List<Entry> connections = lock.runLocked(() -> new ArrayList<>(entries));
List<Entry> connections;
try (AutoLock l = lock.lock())
{
connections = new ArrayList<>(entries);
}
Dumpable.dumpObjects(out, indent, out, connections);
}
@ -208,7 +218,7 @@ public class RoundRobinConnectionPool extends AbstractConnectionPool implements
{
int present = 0;
int active = 0;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
for (Entry entry : entries)
{

View File

@ -27,6 +27,7 @@ import java.util.ArrayDeque;
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<Chunk> chunks = new ArrayDeque<>();
private final String contentType;
private long length = -1;
@ -116,7 +118,7 @@ public class AsyncRequestContent implements Request.Content, Request.Content.Sub
public void fail(Throwable failure)
{
List<Callback> toFail = List.of();
try (AutoLock.WithCondition l = lock.lock())
try (AutoLock l = lock.lock())
{
if (this.failure == null)
{
@ -126,7 +128,7 @@ public class AsyncRequestContent implements Request.Content, Request.Content.Sub
.map(chunk -> chunk.callback)
.collect(Collectors.toList());
chunks.clear();
l.signal();
flush.signal();
}
}
toFail.forEach(c -> c.failed(failure));
@ -291,15 +293,15 @@ public class AsyncRequestContent implements Request.Content, Request.Content.Sub
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 class AsyncRequestContent implements Request.Content, Request.Content.Sub
throw new IOException(failure);
if (chunks.isEmpty())
return;
l.await();
flush.await();
}
}
catch (InterruptedException x)
@ -325,7 +327,7 @@ public class AsyncRequestContent implements Request.Content, Request.Content.Sub
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 class AsyncRequestContent implements Request.Content, Request.Content.Sub
produce = true;
}
}
l.signal();
flush.signal();
}
if (produce)
produce();

View File

@ -47,6 +47,7 @@ import org.eclipse.jetty.util.annotation.ManagedOperation;
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 @@ public class DeploymentManager extends ContainerLifeCycle
}
}
private final AutoLock _lock = new AutoLock();
private final List<AppProvider> _providers = new ArrayList<AppProvider>();
private final AppLifeCycle _lifecycle = new AppLifeCycle();
private final Queue<AppEntry> _apps = new ConcurrentLinkedQueue<AppEntry>();
@ -564,11 +566,12 @@ public class DeploymentManager extends ContainerLifeCycle
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);
}
/**

View File

@ -309,7 +309,7 @@ public class HttpConnectionOverFCGI extends AbstractConnection implements IConne
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 @@ public class HttpConnectionOverFCGI extends AbstractConnection implements IConne
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)

View File

@ -53,12 +53,18 @@ public class Flusher
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()

View File

@ -340,7 +340,7 @@ public class RawHTTP2ProxyTest
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<FrameInfo> deque = frames.computeIfAbsent(stream, s -> new ArrayDeque<>());
deque.offer(new FrameInfo(frame, callback));
@ -364,7 +364,10 @@ public class RawHTTP2ProxyTest
{
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 @@ public class RawHTTP2ProxyTest
{
Stream proxyToServerStream = null;
Session proxyToServerSession = null;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
for (Map.Entry<Stream, Deque<FrameInfo>> entry : frames.entrySet())
{
@ -413,9 +416,12 @@ public class RawHTTP2ProxyTest
@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 @@ public class RawHTTP2ProxyTest
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<Stream, Deque<FrameInfo>> entry : frames.entrySet())
{
@ -625,7 +631,7 @@ public class RawHTTP2ProxyTest
{
if (LOGGER.isDebugEnabled())
LOGGER.debug("SPC queueing {} for {} on {}", frame, stream, stream.getSession());
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
Deque<FrameInfo> deque = frames.computeIfAbsent(stream, s -> new ArrayDeque<>());
deque.offer(new FrameInfo(frame, callback));
@ -677,7 +683,10 @@ public class RawHTTP2ProxyTest
private void link(Stream proxyToServerStream, Stream clientToProxyStream)
{
lock.runLocked(() -> streams.put(proxyToServerStream, clientToProxyStream));
try (AutoLock l = lock.lock())
{
streams.put(proxyToServerStream, clientToProxyStream);
}
iterate();
}
}

View File

@ -192,7 +192,10 @@ public class HTTP2Connection extends AbstractConnection implements WriteFlusher.
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 class HTTP2Connection extends AbstractConnection implements WriteFlusher.
private Runnable pollTask()
{
return lock.runLocked(tasks::poll);
try (AutoLock l = lock.lock())
{
return tasks.poll();
}
}
@Override

View File

@ -66,7 +66,7 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable
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 class HTTP2Flusher extends IteratingCallback implements Dumpable
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 class HTTP2Flusher extends IteratingCallback implements Dumpable
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 class HTTP2Flusher extends IteratingCallback implements Dumpable
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 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable
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 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable
Throwable closed;
Set<Entry> allEntries;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
closed = terminated;
terminated = x;
@ -348,7 +354,7 @@ public class HTTP2Flusher extends IteratingCallback implements Dumpable
void terminate(Throwable cause)
{
Throwable closed;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
closed = terminated;
terminated = cause;

View File

@ -1827,7 +1827,7 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio
{
if (streamId <= 0)
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
streamId = localStreamIds.getAndAdd(2);
slots.offer(slot);
@ -1835,14 +1835,20 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio
}
else
{
lock.runLocked(() -> slots.offer(slot));
try (AutoLock l = lock.lock())
{
slots.offer(slot);
}
}
return streamId;
}
private void releaseSlotFlushAndFail(Slot slot, Promise<Stream> promise, Throwable x)
{
lock.runLocked(() -> slots.remove(slot));
try (AutoLock l = lock.lock())
{
slots.remove(slot);
}
flush();
promise.failed(x);
}
@ -1866,7 +1872,7 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio
while (true)
{
ControlEntry entry;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (flushing == null)
flushing = thread;

View File

@ -143,7 +143,7 @@ public class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
@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 class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
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 class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
@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 @@ public class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
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 @@ public class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
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 class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
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 @@ public class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
while (true)
{
DataEntry dataEntry;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (dataQueue.isEmpty() || dataDemand == 0)
{
@ -459,12 +468,15 @@ public class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
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 @@ public class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
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 class HTTP2Stream extends IdleTimeout implements IStream, Callback, Dumpa
private Callback endWrite()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
Callback callback = sendCallback;
sendCallback = null;

View File

@ -173,7 +173,11 @@ public abstract class HTTP2StreamEndPoint implements EndPoint
@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 abstract class HTTP2StreamEndPoint implements EndPoint
if (source.hasRemaining())
{
lock.runLocked(() -> dataQueue.offerFirst(entry));
try (AutoLock l = lock.lock())
{
dataQueue.offerFirst(entry);
}
}
else
{
@ -543,13 +550,19 @@ public abstract class HTTP2StreamEndPoint implements EndPoint
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);

View File

@ -271,7 +271,10 @@ public class HttpReceiverOverHTTP2 extends HttpReceiver implements HTTP2Channel.
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 @@ public class HttpReceiverOverHTTP2 extends HttpReceiver implements HTTP2Channel.
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 @@ public class HttpReceiverOverHTTP2 extends HttpReceiver implements HTTP2Channel.
}
}
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
dataInfo = queue.poll();
if (LOG.isDebugEnabled())
@ -346,7 +349,7 @@ public class HttpReceiverOverHTTP2 extends HttpReceiver implements HTTP2Channel.
private boolean active(boolean resume)
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (active)
{
@ -379,7 +382,7 @@ public class HttpReceiverOverHTTP2 extends HttpReceiver implements HTTP2Channel.
*/
private boolean stall()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (resume)
{
@ -399,7 +402,7 @@ public class HttpReceiverOverHTTP2 extends HttpReceiver implements HTTP2Channel.
private void reset()
{
dataInfo = null;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
queue.clear();
active = false;

View File

@ -288,15 +288,27 @@ public class HTTP2ServerConnection extends HTTP2Connection
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)

View File

@ -445,7 +445,7 @@ public class HttpTransportOverHTTP2 implements HttpTransport
private Throwable sending(Callback callback, boolean commit)
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
switch (_state)
{
@ -473,7 +473,7 @@ public class HttpTransportOverHTTP2 implements HttpTransport
{
Callback callback;
boolean commit;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_state != State.SENDING)
{
@ -497,7 +497,7 @@ public class HttpTransportOverHTTP2 implements HttpTransport
{
Callback callback;
boolean commit;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_state != State.SENDING)
{
@ -519,7 +519,7 @@ public class HttpTransportOverHTTP2 implements HttpTransport
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 @@ public class HttpTransportOverHTTP2 implements HttpTransport
@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();
}
}

View File

@ -31,6 +31,7 @@ import java.nio.charset.StandardCharsets;
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<ByteBuffer> _inQ = new ArrayDeque<>();
private ByteBuffer _out;
private boolean _growOutput;
@ -125,9 +127,9 @@ public class ByteArrayEndPoint extends AbstractEndPoint
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 class ByteArrayEndPoint extends AbstractEndPoint
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 class ByteArrayEndPoint extends AbstractEndPoint
{
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 @@ public class ByteArrayEndPoint extends AbstractEndPoint
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 class ByteArrayEndPoint extends AbstractEndPoint
if (!idle)
{
notIdle();
lock.signalAll();
_hasOutput.signalAll();
}
}
return flushed;
@ -445,11 +447,11 @@ public class ByteArrayEndPoint extends AbstractEndPoint
@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();
}

View File

@ -254,7 +254,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable
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 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable
LOG.debug("Wakeup {}", this);
Selector selector = null;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_selecting)
{
@ -384,7 +384,10 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable
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 class ManagedSelector extends ContainerLifeCycle implements Dumpable
{
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 class ManagedSelector extends ContainerLifeCycle implements Dumpable
private void processUpdates()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
Deque<SelectorUpdate> updates = _updates;
_updates = _updateable;
@ -542,7 +545,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable
Selector selector;
int updates;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
updates = _updates.size();
_selecting = updates == 0;
@ -578,7 +581,7 @@ public class ManagedSelector extends ContainerLifeCycle implements Dumpable
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;

View File

@ -319,7 +319,7 @@ public class SocketChannelEndPoint extends AbstractEndPoint implements ManagedSe
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 class SocketChannelEndPoint extends AbstractEndPoint implements ManagedSe
{
int oldInterestOps;
int newInterestOps;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_updatePending = false;
oldInterestOps = _currentInterestOps;
@ -405,7 +405,7 @@ public class SocketChannelEndPoint extends AbstractEndPoint implements ManagedSe
int oldInterestOps;
int newInterestOps;
boolean pending;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
pending = _updatePending;
oldInterestOps = _desiredInterestOps;

View File

@ -516,7 +516,7 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr
{
// 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 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr
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 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr
{
// 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 class SslConnection extends AbstractConnection implements Connection.Upgr
{
try
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (LOG.isDebugEnabled())
LOG.debug(">fill {}", SslConnection.this);
@ -813,7 +816,7 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr
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 class SslConnection extends AbstractConnection implements Connection.Upgr
{
try
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (LOG.isDebugEnabled())
{
@ -1147,7 +1150,7 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr
{
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 class SslConnection extends AbstractConnection implements Connection.Upgr
{
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 class SslConnection extends AbstractConnection implements Connection.Upgr
// 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 class SslConnection extends AbstractConnection implements Connection.Upgr
{
endPoint.write(Callback.from(() ->
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_flushState = FlushState.IDLE;
releaseEncryptedOutputBuffer();
@ -1454,7 +1457,7 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr
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 class SslConnection extends AbstractConnection implements Connection.Upgr
{
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 @@ public class SslConnection extends AbstractConnection implements Connection.Upgr
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);

View File

@ -36,9 +36,9 @@ import org.eclipse.jetty.util.thread.AutoLock;
public class UserInfo
{
private final AutoLock _lock = new AutoLock();
protected final List<String> _roleNames = new ArrayList<>();
private final String _userName;
private final Credential _credential;
private String _userName;
private Credential _credential;
protected List<String> _roleNames = new ArrayList<>();
protected boolean _rolesLoaded = false;
/**
@ -81,7 +81,7 @@ public class UserInfo
public void fetchRoles() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (!_rolesLoaded)
{

View File

@ -41,12 +41,12 @@ import org.slf4j.LoggerFactory;
* This is an object factory that produces a jndi naming
* context based on a classloader.
* <p>
* It is used for the {@code java:comp} context.
* It is used for the <code>java:comp</code> context.
* <p>
* This object factory is bound at {@code java:comp}. When a
* This object factory is bound at <code>java:comp</code>. 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 <code>java:comp/env</code>
* specific to a webapp).
* <p>
* 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<Context> __threadContext = new ThreadLocal<>();
private static final ThreadLocal<Context> __threadContext = new ThreadLocal<Context>();
/**
* Threadlocal for setting a classloader which must be used
* when finding the comp context.
*/
private static final ThreadLocal<ClassLoader> __threadClassLoader = new ThreadLocal<>();
private static final ThreadLocal<ClassLoader> __threadClassLoader = new ThreadLocal<ClassLoader>();
private static final AutoLock __lock = new AutoLock();
@ -92,6 +92,8 @@ public class ContextFactory implements ObjectFactory
* <p>
* 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 class ContextFactory implements ObjectFactory
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 class ContextFactory implements ObjectFactory
//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 class ContextFactory implements ObjectFactory
{
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 class ContextFactory implements ObjectFactory
//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 class ContextFactory implements ObjectFactory
{
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 class ContextFactory implements ObjectFactory
*/
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 class ContextFactory implements ObjectFactory
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 class ContextFactory implements ObjectFactory
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);
}

View File

@ -297,7 +297,7 @@ public class DigestAuthenticator extends LoginAuthenticator
public boolean seen(int count)
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (count >= _seen.size())
return true;

View File

@ -33,6 +33,7 @@ import java.util.Set;
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<String, ConnectionFactory> _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 abstract class AbstractConnector extends ContainerLifeCycle implements Co
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 abstract class AbstractConnector extends ContainerLifeCycle implements Co
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 abstract class AbstractConnector extends ContainerLifeCycle implements Co
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();

View File

@ -125,7 +125,7 @@ public class AcceptRateLimit extends AbstractLifeCycle implements SelectorManage
@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 @@ public class AcceptRateLimit extends AbstractLifeCycle implements SelectorManage
@Override
protected void doStart() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_server != null)
{
@ -170,7 +170,7 @@ public class AcceptRateLimit extends AbstractLifeCycle implements SelectorManage
@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 @@ public class AcceptRateLimit extends AbstractLifeCycle implements SelectorManage
@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 class AcceptRateLimit extends AbstractLifeCycle implements SelectorManage
if (!_limiting)
{
_limiting = true;
LOG.warn("AcceptLimit rate exceeded {}>{} on {}", rate, _acceptRateLimit, _connectors);
limit();
}
@ -237,7 +238,7 @@ public class AcceptRateLimit extends AbstractLifeCycle implements SelectorManage
@Override
public void run()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_task = null;
if (!isRunning())

View File

@ -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<AbstractConnector> _connectors = new ArrayList<>();
private final Set<SelectableChannel> _accepting = new HashSet<>();
private final Server _server;
private int _connections;
private int _maxConnections;
private long _idleTimeout;
@ -110,24 +110,33 @@ public class ConnectionLimit extends AbstractLifeCycle implements Listener, Sele
@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 @@ public class ConnectionLimit extends AbstractLifeCycle implements Listener, Sele
@Override
protected void doStop() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
for (AbstractConnector c : _connectors)
{
@ -222,7 +231,7 @@ public class ConnectionLimit extends AbstractLifeCycle implements Listener, Sele
@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 class ConnectionLimit extends AbstractLifeCycle implements Listener, Sele
@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 class ConnectionLimit extends AbstractLifeCycle implements Listener, Sele
@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 class ConnectionLimit extends AbstractLifeCycle implements Listener, Sele
@Override
public void onClosed(Connection connection)
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_connections--;
if (LOG.isDebugEnabled())

View File

@ -21,7 +21,6 @@ package org.eclipse.jetty.server;
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 @@ public class HttpChannelState
return _lock.lock();
}
<R> R runLocked(Supplier<R> 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 class HttpChannelState
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 @@ public class HttpChannelState
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 class HttpChannelState
public boolean partialResponse()
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
switch (_outputState)
{
@ -294,7 +309,7 @@ public class HttpChannelState
public boolean completeResponse()
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
switch (_outputState)
{
@ -311,7 +326,7 @@ public class HttpChannelState
public boolean isResponseCommitted()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = lock())
{
switch (_outputState)
{
@ -325,12 +340,15 @@ public class HttpChannelState
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 class HttpChannelState
*/
public Action handling()
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("handling {}", toStringLocked());
@ -396,7 +414,7 @@ public class HttpChannelState
*/
protected Action unhandle()
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("unhandle {}", toStringLocked());
@ -515,7 +533,7 @@ public class HttpChannelState
{
final List<AsyncListener> lastAsyncListeners;
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("startAsync {}", toStringLocked());
@ -564,7 +582,7 @@ public class HttpChannelState
{
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 class HttpChannelState
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 @@ public class HttpChannelState
{
final List<AsyncListener> listeners;
AsyncContextEvent event;
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("onTimeout {}", toStringLocked());
@ -676,7 +694,7 @@ public class HttpChannelState
{
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 class HttpChannelState
// 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 @@ public class HttpChannelState
{
final AsyncContextEvent asyncEvent;
final List<AsyncListener> asyncListeners;
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("thrownException " + getStatusStringLocked(), th);
@ -809,7 +827,7 @@ public class HttpChannelState
});
// check the actions of the listeners
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_requestState == RequestState.ASYNC && !_sendError)
{
@ -881,7 +899,7 @@ public class HttpChannelState
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 class HttpChannelState
protected void completing()
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("completing {}", toStringLocked());
@ -943,7 +961,7 @@ public class HttpChannelState
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 @@ public class HttpChannelState
}
event.completed();
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
_requestState = RequestState.COMPLETED;
if (_state == State.WAITING)
@ -1015,7 +1033,7 @@ public class HttpChannelState
protected void recycle()
{
cancelTimeout();
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("recycle {}", toStringLocked());
@ -1044,7 +1062,7 @@ public class HttpChannelState
public void upgrade()
{
cancelTimeout();
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("upgrade {}", toStringLocked());
@ -1074,8 +1092,7 @@ public class HttpChannelState
protected void cancelTimeout()
{
AsyncContextEvent event = runLocked(() -> _event);
cancelTimeout(event);
cancelTimeout(getAsyncContextEvent());
}
protected void cancelTimeout(AsyncContextEvent event)
@ -1086,33 +1103,48 @@ public class HttpChannelState
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 class HttpChannelState
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 class HttpChannelState
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 class HttpChannelState
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 class HttpChannelState
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 class HttpChannelState
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 class HttpChannelState
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 class HttpChannelState
{
boolean wake = false;
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (LOG.isDebugEnabled())
LOG.debug("onWritePossible {}", toStringLocked());

View File

@ -153,7 +153,7 @@ public class HttpInput extends ServletInputStream implements Runnable
public void recycle()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_content != null)
_content.failed(null);
@ -214,7 +214,7 @@ public class HttpInput extends ServletInputStream implements Runnable
{
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 class HttpInput extends ServletInputStream implements Runnable
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 class HttpInput extends ServletInputStream implements Runnable
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 class HttpInput extends ServletInputStream implements Runnable
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 class HttpInput extends ServletInputStream implements Runnable
if (wake)
wake();
return l;
return read;
}
/**
@ -335,7 +335,7 @@ public class HttpInput extends ServletInputStream implements Runnable
*/
public void asyncReadProduce() throws IOException
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
produceContent();
}
@ -524,6 +524,7 @@ public class HttpInput extends ServletInputStream implements Runnable
*/
protected void blockForContent() throws IOException
{
assert _lock.isHeldByCurrentThread();
try
{
_waitingForContent = true;
@ -562,7 +563,7 @@ public class HttpInput extends ServletInputStream implements Runnable
*/
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 class HttpInput extends ServletInputStream implements Runnable
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 class HttpInput extends ServletInputStream implements Runnable
public boolean consumeAll()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
try
{
@ -665,18 +672,27 @@ public class HttpInput extends ServletInputStream implements Runnable
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 class HttpInput extends ServletInputStream implements Runnable
{
try
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_listener == null)
return true;
@ -712,7 +728,7 @@ public class HttpInput extends ServletInputStream implements Runnable
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 @@ public class HttpInput extends ServletInputStream implements Runnable
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 class HttpInput extends ServletInputStream implements Runnable
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 class HttpInput extends ServletInputStream implements Runnable
private boolean wakeup()
{
assert _lock.isHeldByCurrentThread();
if (_listener != null)
return _channelState.onContentAdded();
_lock.signal();
@ -820,7 +837,7 @@ public class HttpInput extends ServletInputStream implements Runnable
Throwable error;
boolean aeof = false;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
listener = _listener;
@ -909,7 +926,7 @@ public class HttpInput extends ServletInputStream implements Runnable
long consumed;
int q;
Content content;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
state = _state;
consumed = _contentConsumed;

View File

@ -239,7 +239,10 @@ public class HttpOutput extends ServletOutputStream implements Runnable
public void reopen()
{
_channelState.runLocked(() -> _softClose = false);
try (AutoLock l = _channelState.lock())
{
_softClose = false;
}
}
protected Blocker acquireWriteBlockingCallback() throws IOException
@ -276,7 +279,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
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 @@ public class HttpOutput extends ServletOutputStream implements Runnable
public void softClose()
{
_channelState.runLocked(() -> _softClose = true);
try (AutoLock l = _channelState.lock())
{
_softClose = true;
}
}
public void complete(Callback callback)
@ -392,7 +398,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
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 class HttpOutput extends ServletOutputStream implements Runnable
*/
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 class HttpOutput extends ServletOutputStream implements Runnable
{
ByteBuffer content = null;
Blocker blocker = null;
try (AutoLock ignored = _channelState.lock())
try (AutoLock l = _channelState.lock())
{
if (_onError != null)
{
@ -597,7 +603,10 @@ public class HttpOutput extends ServletOutputStream implements Runnable
public ByteBuffer getBuffer()
{
return _channelState.runLocked(this::acquireBuffer);
try (AutoLock l = _channelState.lock())
{
return acquireBuffer();
}
}
private ByteBuffer acquireBuffer()
@ -622,12 +631,15 @@ public class HttpOutput extends ServletOutputStream implements Runnable
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 class HttpOutput extends ServletOutputStream implements Runnable
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 class HttpOutput extends ServletOutputStream implements Runnable
// 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 class HttpOutput extends ServletOutputStream implements Runnable
// 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 class HttpOutput extends ServletOutputStream implements Runnable
// 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 class HttpOutput extends ServletOutputStream implements Runnable
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 class HttpOutput extends ServletOutputStream implements Runnable
public void recycle()
{
try (AutoLock ignored = _channelState.lock())
try (AutoLock l = _channelState.lock())
{
_state = State.OPEN;
_apiState = ApiState.BLOCKING;
@ -1359,7 +1371,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
public void resetBuffer()
{
try (AutoLock ignored = _channelState.lock())
try (AutoLock l = _channelState.lock())
{
_interceptor.resetBuffer();
if (BufferUtil.hasContent(_aggregate))
@ -1374,7 +1386,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
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 class HttpOutput extends ServletOutputStream implements Runnable
@Override
public boolean isReady()
{
try (AutoLock ignored = _channelState.lock())
try (AutoLock l = _channelState.lock())
{
switch (_apiState)
{
@ -1420,7 +1432,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
{
Throwable error = null;
try (AutoLock ignored = _channelState.lock())
try (AutoLock l = _channelState.lock())
{
if (_onError != null)
{
@ -1471,7 +1483,10 @@ public class HttpOutput extends ServletOutputStream implements Runnable
@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

View File

@ -103,7 +103,7 @@ public class MultiPartFormInputStream
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 class MultiPartFormInputStream
if (((ServletInputStream)in).isFinished())
{
_in = null;
_state = State.PARSED;
state = State.PARSED;
return;
}
}
@ -410,24 +410,24 @@ public class MultiPartFormInputStream
*/
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 @@ public class MultiPartFormInputStream
*/
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 @@ public class MultiPartFormInputStream
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 @@ public class MultiPartFormInputStream
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());
}
}

View File

@ -177,7 +177,7 @@ public class RequestLogWriter extends AbstractLifeCycle implements RequestLog.Wr
@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 class RequestLogWriter extends AbstractLifeCycle implements RequestLog.Wr
@Override
protected void doStart() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_filename != null)
{
@ -204,8 +204,8 @@ public class RequestLogWriter extends AbstractLifeCycle implements RequestLog.Wr
}
_out = _fileOut;
_writer = new OutputStreamWriter(_out);
super.doStart();
}
super.doStart();
}
public void setTimeZone(String timeZone)
@ -222,9 +222,9 @@ public class RequestLogWriter extends AbstractLifeCycle implements RequestLog.Wr
@Override
protected void doStop() throws Exception
{
super.doStop();
try (AutoLock ignored = _lock.lock())
{
super.doStop();
try
{
if (_writer != null)

View File

@ -377,19 +377,22 @@ public class ResourceService
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;
}

View File

@ -98,9 +98,8 @@ public class ShutdownMonitor
/**
* Creates a ShutdownMonitor using configuration from the System properties.
* <p>
* {@code STOP.PORT} = the port to listen on (empty, null, or values less than 0 disable the stop ability)
* <br>
* {@code STOP.KEY} = the magic key/passphrase to allow the stop<br>
* <code>STOP.PORT</code> = the port to listen on (empty, null, or values less than 0 disable the stop ability)<br>
* <code>STOP.KEY</code> = the magic key/passphrase to allow the stop<br>
* <p>
* Note: server socket will only listen on localhost, and a successful stop will issue a System.exit() call.
*/
@ -115,17 +114,26 @@ public class 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 @@ public class ShutdownMonitor
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 class ShutdownMonitor
*/
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 class ShutdownMonitor
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 class ShutdownMonitor
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 class ShutdownMonitor
protected void start() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (alive)
{
@ -216,28 +233,31 @@ public class ShutdownMonitor
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 @@ public class ShutdownMonitor
private void stopLifeCycles(Predicate<LifeCycle> predicate, boolean destroy)
{
List<LifeCycle> lifeCycles = _lock.runLocked(() -> new ArrayList<>(_lifeCycles));
List<LifeCycle> lifeCycles;
try (AutoLock l = _lock.lock())
{
lifeCycles = new ArrayList<>(_lifeCycles);
}
for (LifeCycle l : lifeCycles)
{
try

View File

@ -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> __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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
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<EventListener> _programmaticListeners = new CopyOnWriteArrayList<>();
private final List<ServletContextListener> _servletContextListeners = new CopyOnWriteArrayList<>();
private final List<ServletContextListener> _destroyServletContextListeners = new ArrayList<>();
@ -214,13 +222,15 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
private final Set<EventListener> _durableListeners = new HashSet<>();
private String[] _protectedTargets;
private final CopyOnWriteArrayList<AliasCheck> _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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
*/
public ClassLoader getClassLoader()
{
return _lock.runLocked(() -> _classLoader);
return _classLoader;
}
/**
@ -524,10 +534,9 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
@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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
*/
public boolean isAvailable()
{
return _lock.runLocked(() -> _availability == Availability.AVAILABLE);
return _availability == Availability.AVAILABLE;
}
/**
@ -749,7 +758,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
*/
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 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
_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 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
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 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
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 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
}
}
ClassLoader classLoader = getClassLoader();
if (classLoader != null)
currentThread.setContextClassLoader(classLoader);
if (_classLoader != null)
currentThread.setContextClassLoader(_classLoader);
try
{
@ -1229,7 +1235,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
exitScope(baseRequest);
// reset the classloader
if (classLoader != null)
if (_classLoader != null)
currentThread.setContextClassLoader(oldClassloader);
// reset the context and servlet path.
@ -1356,6 +1362,8 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
*/
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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
}
// 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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
exitScope(request);
__context.set(oldContext);
if (classLoader != null)
Thread.currentThread().setContextClassLoader(oldClassLoader);
if (oldClassloader != null)
{
currentThread.setContextClassLoader(oldClassloader);
}
}
}
@ -1496,7 +1504,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
*/
public void setClassLoader(ClassLoader classLoader)
{
_lock.runLocked(() -> _classLoader = classLoader);
_classLoader = classLoader;
}
/**
@ -1782,11 +1790,13 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
@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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
@Override
public Enumeration<String> getAttributeNames()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
HashSet<String> set = new HashSet<>();
Enumeration<String> e = super.getAttributeNames();
@ -2290,7 +2300,7 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
@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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
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 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
@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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
try
{
ClassLoader classLoader = ContextHandler.this.getClassLoader();
@SuppressWarnings("unchecked")
Class<? extends EventListener> clazz = classLoader == null
? Loader.loadClass(className)
: (Class<? extends EventListener>)classLoader.loadClass(className);
@SuppressWarnings(
{"unchecked", "rawtypes"})
Class<? extends EventListener> clazz = _classLoader == null ? Loader.loadClass(className) : (Class)_classLoader.loadClass(className);
addListener(clazz);
}
catch (ClassNotFoundException e)
@ -2445,12 +2454,10 @@ public class ContextHandler extends ScopedHandler implements Attributes, Gracefu
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 class ContextHandler extends ScopedHandler implements Attributes, Gracefu
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;
}
}

View File

@ -52,7 +52,9 @@ import org.slf4j.LoggerFactory;
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 class DefaultSessionIdManager extends ContainerLifeCycle implements Sessi
// 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 class DefaultSessionIdManager extends ContainerLifeCycle implements Sessi
if (!StringUtil.isBlank(_workerName))
id = _workerName + id;
id = id + COUNTER.getAndIncrement();
id = id + Long.toString(COUNTER.getAndIncrement());
}
}
return id;

View File

@ -127,7 +127,7 @@ public class HouseKeeper extends AbstractLifeCycle
*/
protected void startScavenging() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_scheduler != null)
{
@ -149,7 +149,7 @@ public class HouseKeeper extends AbstractLifeCycle
*/
protected void stopScavenging() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_task != null)
{
@ -170,7 +170,7 @@ public class HouseKeeper extends AbstractLifeCycle
@Override
protected void doStop() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
stopScavenging();
_scheduler = null;

View File

@ -24,6 +24,7 @@ import java.util.Enumeration;
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 class Session implements SessionHandler.SessionIf
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 class Session implements SessionHandler.SessionIf
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 class Session implements SessionHandler.SessionIf
*/
public long getRequests()
{
return _lock.runLocked(() -> _requests);
try (AutoLock l = _lock.lock())
{
return _requests;
}
}
public void setExtendedId(String extendedId)
@ -216,12 +221,15 @@ public class Session implements SessionHandler.SessionIf
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 @@ public class Session implements SessionHandler.SessionIf
protected boolean access(long time)
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (!isValid() || !isResident())
return false;
@ -254,7 +262,7 @@ public class Session implements SessionHandler.SessionIf
protected void complete()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_requests--;
@ -281,7 +289,10 @@ public class Session implements SessionHandler.SessionIf
*/
protected boolean isExpiredAt(long time)
{
return _lock.runLocked(() -> _sessionData.isExpiredAt(time));
try (AutoLock l = _lock.lock())
{
return _sessionData.isExpiredAt(time);
}
}
/**
@ -293,7 +304,10 @@ public class Session implements SessionHandler.SessionIf
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 class Session implements SessionHandler.SessionIf
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 class Session implements SessionHandler.SessionIf
@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 class Session implements SessionHandler.SessionIf
@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 class Session implements SessionHandler.SessionIf
@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 class Session implements SessionHandler.SessionIf
{
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 @@ public class Session implements SessionHandler.SessionIf
@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 @@ public class Session implements SessionHandler.SessionIf
@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 class Session implements SessionHandler.SessionIf
@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 class Session implements SessionHandler.SessionIf
@Override
public Enumeration<String> getAttributeNames()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
checkValidForRead();
final Iterator<String> itor = _sessionData.getKeys().iterator();
@ -688,7 +716,7 @@ public class Session implements SessionHandler.SessionIf
@Deprecated(since = "Servlet API 2.2")
public String[] getValueNames() throws IllegalStateException
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
checkValidForRead();
Iterator<String> itor = _sessionData.getKeys().iterator();
@ -707,7 +735,7 @@ public class Session implements SessionHandler.SessionIf
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 class Session implements SessionHandler.SessionIf
String id = null;
String extendedId = null;
try (AutoLock.WithCondition lock = _lock.lock())
try (AutoLock l = _lock.lock())
{
while (true)
{
@ -764,7 +792,7 @@ public class Session implements SessionHandler.SessionIf
case CHANGING:
try
{
lock.await();
_stateChangeCompleted.await();
}
catch (InterruptedException e)
{
@ -787,7 +815,7 @@ public class Session implements SessionHandler.SessionIf
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 class Session implements SessionHandler.SessionIf
setIdChanged(true);
_state = State.VALID;
lock.signalAll();
_stateChangeCompleted.signalAll();
break;
case INVALID:
@ -877,7 +905,7 @@ public class Session implements SessionHandler.SessionIf
{
boolean result = false;
try (AutoLock.WithCondition lock = _lock.lock())
try (AutoLock l = _lock.lock())
{
while (true)
{
@ -902,7 +930,7 @@ public class Session implements SessionHandler.SessionIf
{
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 @@ public class Session implements SessionHandler.SessionIf
*/
protected void finishInvalidate() throws IllegalStateException
{
try (AutoLock.WithCondition lock = _lock.lock())
try (AutoLock l = _lock.lock())
{
try
{
@ -965,7 +993,7 @@ public class Session implements SessionHandler.SessionIf
// mark as invalid
_state = State.INVALID;
_handler.recordSessionTime(this);
lock.signalAll();
_stateChangeCompleted.signalAll();
}
}
}
@ -973,7 +1001,7 @@ public class Session implements SessionHandler.SessionIf
@Override
public boolean isNew() throws IllegalStateException
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
checkValidForRead();
return _newSession;
@ -982,12 +1010,18 @@ public class Session implements SessionHandler.SessionIf
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 class Session implements SessionHandler.SessionIf
@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(),

View File

@ -124,13 +124,16 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest
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

View File

@ -173,7 +173,7 @@ public abstract class BaseHolder<T> extends AbstractLifeCycle implements Dumpabl
protected void setInstance(T instance)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
_instance = instance;
if (instance == null)
@ -185,12 +185,15 @@ public abstract class BaseHolder<T> extends AbstractLifeCycle implements Dumpabl
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 abstract class BaseHolder<T> extends AbstractLifeCycle implements Dumpabl
*/
public boolean isInstance()
{
return _lock.runLocked(() -> _instance != null);
try (AutoLock l = lock())
{
return _instance != null;
}
}
@Override

View File

@ -103,7 +103,7 @@ public class FilterHolder extends Holder<Filter>
@Override
public void initialize() throws Exception
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_filter != null)
return;
@ -136,7 +136,7 @@ public class FilterHolder extends Holder<Filter>
@Override
protected Filter createInstance() throws Exception
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
Filter filter = super.createInstance();
if (filter == null)

View File

@ -101,7 +101,7 @@ public abstract class Holder<T> extends BaseHolder<T>
@Override
protected void setInstance(T instance)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
super.setInstance(instance);
if (getName() == null)

View File

@ -164,7 +164,7 @@ public class Invoker extends HttpServlet
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 @@ public class Invoker extends HttpServlet
if (entry != null && !entry.equals(_invokerEntry))
{
// Use the holder
holder = entry.getServletHolder();
holder = (ServletHolder)entry.getServletHolder();
}
else
{

View File

@ -108,7 +108,7 @@ public class ListenerHolder extends BaseHolder<EventListener>
@Override
protected EventListener createInstance() throws Exception
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
EventListener listener = super.createInstance();
if (listener == null)

View File

@ -81,7 +81,7 @@ import org.slf4j.LoggerFactory;
* <P>
* 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 <code>org.eclipse.jetty.webapp.WebAppContext</code>.
* <p>
* 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<String, FilterHolder> _filterNameMap = new HashMap<>();
private List<FilterMapping> _filterPathMappings;
private MultiMap<FilterMapping> _filterNameMappings;
private final Map<String, MappedServlet> _servletNameMap = new HashMap<>();
private PathMappings<MappedServlet> _servletPathMap;
private ListenerHolder[] _listeners = new ListenerHolder[0];
private boolean _initialized = false;
@SuppressWarnings("unchecked")
protected final ConcurrentMap<String, FilterChain>[] _chainCache = new ConcurrentMap[FilterMapping.ALL];
@SuppressWarnings("unchecked")
protected final Queue<String>[] _chainLRU = new Queue[FilterMapping.ALL];
/**
* Constructor.
*/
public ServletHandler()
{
}
AutoLock lock()
{
return _lock.lock();
@ -126,7 +138,7 @@ public class ServletHandler extends ScopedHandler
@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 class ServletHandler extends ScopedHandler
@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 (getServletMapping("/") == null && isEnsureDefaultServlet())
{
if (LOG.isDebugEnabled())
LOG.debug("Adding Default404Servlet to {}", this);
addServletWithMapping(Default404Servlet.class, "/");
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 (_contextHandler == null)
initialize();
super.doStart();
}
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();
}
/**
@ -226,115 +241,118 @@ public class ServletHandler extends ScopedHandler
@Override
protected void doStop() throws Exception
{
super.doStop();
// Stop filters
List<FilterHolder> filterHolders = new ArrayList<>();
List<FilterMapping> filterMappings = ArrayUtil.asMutableList(_filterMappings);
if (_filters != null)
try (AutoLock l = lock())
{
for (int i = _filters.length; i-- > 0; )
super.doStop();
// Stop filters
List<FilterHolder> filterHolders = new ArrayList<>();
List<FilterMapping> filterMappings = ArrayUtil.asMutableList(_filterMappings);
if (_filters != null)
{
FilterHolder filter = _filters[i];
try
for (int i = _filters.length; i-- > 0; )
{
filter.stop();
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
}
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
}
}
//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;
//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;
_matchAfterIndex = (_filterMappings == null || _filterMappings.length == 0 ? -1 : _filterMappings.length - 1);
_matchBeforeIndex = -1;
// Stop servlets
List<ServletHolder> servletHolders = new ArrayList<>(); //will be remaining servlets
List<ServletMapping> servletMappings = ArrayUtil.asMutableList(_servletMappings); //will be remaining mappings
if (_servlets != null)
{
for (int i = _servlets.length; i-- > 0; )
// Stop servlets
List<ServletHolder> servletHolders = new ArrayList<>(); //will be remaining servlets
List<ServletMapping> servletMappings = ArrayUtil.asMutableList(_servletMappings); //will be remaining mappings
if (_servlets != null)
{
ServletHolder servlet = _servlets[i];
try
for (int i = _servlets.length; i-- > 0; )
{
servlet.stop();
}
catch (Exception e)
{
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<ListenerHolder> 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<ListenerHolder> listenerHolders = new ArrayList<>();
if (_listeners != null)
{
ListenerHolder listener = _listeners[i];
try
for (int i = _listeners.length; i-- > 0; )
{
listener.stop();
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);
}
catch (Exception e)
{
LOG.warn("Unable to stop listener {}", listener, e);
}
if (listener.getSource() == Source.EMBEDDED)
listenerHolders.add(listener);
}
}
ListenerHolder[] listeners = (ListenerHolder[])LazyList.toArray(listenerHolders, ListenerHolder.class);
updateBeans(_listeners, listeners);
_listeners = listeners;
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;
//will be regenerated on next start
_filterPathMappings = null;
_filterNameMappings = null;
_servletPathMap = null;
_initialized = false;
}
}
protected IdentityService getIdentityService()
@ -858,7 +876,7 @@ public class ServletHandler extends ScopedHandler
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 class ServletHandler extends ScopedHandler
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 class ServletHandler extends ScopedHandler
try
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (holder != null && !containsFilterHolder(holder))
setFilters(ArrayUtil.addToArray(holders, holder, FilterHolder.class));
@ -1039,7 +1057,7 @@ public class ServletHandler extends ScopedHandler
try
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (holder != null && !containsFilterHolder(holder))
setFilters(ArrayUtil.addToArray(holders, holder, FilterHolder.class));
@ -1068,7 +1086,7 @@ public class ServletHandler extends ScopedHandler
{
if (filter != null)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (!containsFilterHolder(filter))
setFilters(ArrayUtil.addToArray(getFilters(), filter, FilterHolder.class));
@ -1088,7 +1106,7 @@ public class ServletHandler extends ScopedHandler
if (filter == null)
return;
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (!containsFilterHolder(filter))
setFilters(ArrayUtil.addToArray(getFilters(), filter, FilterHolder.class));
@ -1239,7 +1257,7 @@ public class ServletHandler extends ScopedHandler
protected void updateNameMappings()
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
// update filter name map
_filterNameMap.clear();
@ -1268,7 +1286,7 @@ public class ServletHandler extends ScopedHandler
protected void updateMappings()
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
// update filter mappings
if (_filterMappings == null)
@ -1427,7 +1445,7 @@ public class ServletHandler extends ScopedHandler
protected boolean containsFilterHolder(FilterHolder holder)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_filters == null)
return false;
@ -1442,7 +1460,7 @@ public class ServletHandler extends ScopedHandler
protected boolean containsServletHolder(ServletHolder holder)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_servlets == null)
return false;
@ -1479,7 +1497,7 @@ public class ServletHandler extends ScopedHandler
public void setFilters(FilterHolder[] holders)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (holders != null)
{
@ -1514,7 +1532,7 @@ public class ServletHandler extends ScopedHandler
*/
public void setServlets(ServletHolder[] holders)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (holders != null)
{

View File

@ -256,7 +256,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
*/
public void setUserRoleLink(String name, String link)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_roleMap == null)
_roleMap = new HashMap<>();
@ -273,7 +273,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
*/
public String getUserRoleLink(String name)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_roleMap == null)
return name;
@ -399,7 +399,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
_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 class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
public void initialize()
throws Exception
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_servlet == null && (_initOnStartup || isInstance()))
{
@ -424,7 +424,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
public void doStop()
throws Exception
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
Servlet servlet = _servlet;
if (servlet != null)
@ -470,7 +470,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
public Servlet getServlet()
throws ServletException
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_servlet == null && isRunning())
{
@ -531,7 +531,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
private Servlet makeUnavailable(UnavailableException e)
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
_servlet = new UnavailableServlet(e, _servlet);
return _servlet;
@ -562,7 +562,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
private void initServlet()
throws ServletException
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
if (_servlet == null)
_servlet = getInstance();
@ -1016,12 +1016,12 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
private class SingleThreadedWrapper implements Servlet
{
private final Stack<Servlet> _stack = new Stack<>();
Stack<Servlet> _stack = new Stack<>();
@Override
public void destroy()
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
while (_stack.size() > 0)
{
@ -1053,7 +1053,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
@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 class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
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 class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
}
finally
{
try (AutoLock ignored = lock())
try (AutoLock l = lock())
{
_stack.push(s);
}
@ -1131,7 +1131,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
@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 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
((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);

View File

@ -1154,7 +1154,7 @@ public class DoSFilter implements Filter
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 class DoSFilter implements Filter
// 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;

View File

@ -44,11 +44,11 @@ import org.eclipse.jetty.util.thread.AutoLock;
* and to emit event source events.</p>
* <p>This servlet supports the following configuration parameters:</p>
* <ul>
* <li>{@code heartBeatPeriod}, that specifies the heartbeat period, in seconds, used to check
* <li><code>heartBeatPeriod</code>, that specifies the heartbeat period, in seconds, used to check
* whether the connection has been closed by the client; defaults to 10 seconds.</li>
* </ul>
*
* <p>NOTE: there is currently no support for {@code last-event-id}.</p>
* <p>NOTE: there is currently no support for <code>last-event-id</code>.</p>
*/
public abstract class EventSourceServlet extends HttpServlet
{
@ -79,6 +79,7 @@ public abstract class EventSourceServlet extends HttpServlet
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
@SuppressWarnings("unchecked")
Enumeration<String> acceptValues = request.getHeaders("Accept");
while (acceptValues.hasMoreElements())
{
@ -145,7 +146,7 @@ public abstract class EventSourceServlet extends HttpServlet
@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 abstract class EventSourceServlet extends HttpServlet
@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 abstract class EventSourceServlet extends HttpServlet
@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 abstract class EventSourceServlet extends HttpServlet
// on the second flush()
try
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
output.write('\r');
flush();
@ -219,7 +220,7 @@ public abstract class EventSourceServlet extends HttpServlet
@Override
public void close()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
closed = true;
heartBeat.cancel(false);
@ -229,7 +230,7 @@ public abstract class EventSourceServlet extends HttpServlet
private void scheduleHeartBeat()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (!closed)
heartBeat = scheduler.schedule(this, heartBeatPeriod, TimeUnit.SECONDS);

View File

@ -79,7 +79,7 @@ public class JSONDateConvertor implements JSON.Convertor
throw new UnsupportedOperationException();
try
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
return _format.parseObject((String)map.get("value"));
}

View File

@ -229,7 +229,7 @@ public class RolloverFileOutputStream extends OutputStream
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 @@ public class RolloverFileOutputStream extends OutputStream
@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 class RolloverFileOutputStream extends OutputStream
@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 class RolloverFileOutputStream extends OutputStream
@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 class RolloverFileOutputStream extends OutputStream
@Override
public void flush() throws IOException
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_out.flush();
}
@ -381,7 +381,7 @@ public class RolloverFileOutputStream extends OutputStream
@Override
public void close() throws IOException
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
try
{

View File

@ -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<Listener> _listeners = new ArrayList<>();
private final Map<String, TimeNSize> _prevScan = new HashMap<>();
private final Map<String, TimeNSize> _currentScan = new HashMap<>();
private final Map<Path, IncludeExcludeSet<PathMatcher, Path>> _scannables = new HashMap<>();
private int _scanInterval;
private int _scanCount = 0;
private FilenameFilter _filter;
private final Map<Path, IncludeExcludeSet<PathMatcher, Path>> _scannables = new HashMap<>();
private volatile boolean _running = false;
private boolean _reportExisting = true;
private boolean _reportDirs = true;
@ -300,7 +300,10 @@ public class Scanner extends AbstractLifeCycle
*/
public int getScanInterval()
{
return _lock.runLocked(() -> _scanInterval);
try (AutoLock l = _lock.lock())
{
return _scanInterval;
}
}
/**
@ -310,7 +313,7 @@ public class Scanner extends AbstractLifeCycle
*/
public void setScanInterval(int scanInterval)
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_scanInterval = scanInterval;
schedule();
@ -334,7 +337,7 @@ public class Scanner extends AbstractLifeCycle
{
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 class Scanner extends AbstractLifeCycle
{
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 class Scanner extends AbstractLifeCycle
{
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<PathMatcher, Path> includesExcludes = _scannables.get(p);
if (includesExcludes == null)
@ -508,7 +517,10 @@ public class Scanner extends AbstractLifeCycle
{
if (listener == null)
return;
_lock.runLocked(() -> _listeners.add(listener));
try (AutoLock l = _lock.lock())
{
_listeners.add(listener);
}
}
/**
@ -520,7 +532,10 @@ public class Scanner extends AbstractLifeCycle
{
if (listener == null)
return;
_lock.runLocked(() -> _listeners.remove(listener));
try (AutoLock l = _lock.lock())
{
_listeners.remove(listener);
}
}
/**
@ -529,7 +544,7 @@ public class Scanner extends AbstractLifeCycle
@Override
public void doStart()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_running)
return;
@ -595,7 +610,7 @@ public class Scanner extends AbstractLifeCycle
@Override
public void doStop()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_running)
{
@ -646,7 +661,7 @@ public class Scanner extends AbstractLifeCycle
*/
public void scan()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
reportScanStart(++_scanCount);
scanFiles();
@ -655,12 +670,12 @@ public class Scanner extends AbstractLifeCycle
_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 class Scanner extends AbstractLifeCycle
*/
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 class Scanner extends AbstractLifeCycle
*/
private void reportDifferences(Map<String, TimeNSize> currentScan, Map<String, TimeNSize> 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<String> oldScanKeys = new HashSet<>(oldScan.keySet());

View File

@ -376,12 +376,15 @@ public class StringUtil
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));
}
}
}

View File

@ -1180,24 +1180,27 @@ public class URIUtil
*/
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);
}
}
}
}

View File

@ -140,7 +140,7 @@ public class UrlEncoded extends MultiMap<String> implements Cloneable
* for parameters without a value. e.g. <code>"blah?a=&amp;b=&amp;c="</code>.
* @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 class UrlEncoded extends MultiMap<String> implements Cloneable
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)
{
map.add(key, "");
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)
{
map.add(key, "");
}
}
}
}
@ -313,72 +316,75 @@ public class UrlEncoded extends MultiMap<String> implements Cloneable
public static void decodeUtf8To(String query, int offset, int length, MultiMap<String> 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)
{
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;
String key = null;
String value = null;
case '=':
if (key != null)
{
int end = offset + length;
for (int i = offset; i < end; i++)
{
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);
break;
}
key = buffer.toReplacedString();
buffer.reset();
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;
default:
buffer.append(c);
break;
}
key = buffer.toReplacedString();
buffer.reset();
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;
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 @@ public class UrlEncoded extends MultiMap<String> implements Cloneable
public static void decode88591To(InputStream in, MultiMap<String> map, int maxLength, int maxKeys)
throws IOException
{
StringBuilder buffer = new StringBuilder();
String key = null;
String value = null;
int b;
int totalLength = 0;
while ((b = in.read()) >= 0)
synchronized (map)
{
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;
StringBuilder buffer = new StringBuilder();
String key = null;
String value = null;
case '=':
if (key != null)
{
int b;
int totalLength = 0;
while ((b = in.read()) >= 0)
{
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);
break;
}
key = buffer.toString();
buffer.setLength(0);
break;
case '+':
buffer.append(' ');
break;
case '%':
int code0 = in.read();
int code1 = in.read();
buffer.append(decodeHexChar(code0, code1));
break;
default:
buffer.append((char)b);
break;
}
key = buffer.toString();
buffer.setLength(0);
break;
case '+':
buffer.append(' ');
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);
}
checkMaxLength(++totalLength, maxLength);
}
if (key != null)
{
value = buffer.length() == 0 ? "" : buffer.toString();
buffer.setLength(0);
map.add(key, value);
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);
}
else if (buffer.length() > 0)
{
map.add(buffer.toString(), "");
}
checkMaxKeys(map, maxKeys);
}
/**
@ -473,71 +482,74 @@ public class UrlEncoded extends MultiMap<String> implements Cloneable
public static void decodeUtf8To(InputStream in, MultiMap<String> map, int maxLength, int maxKeys)
throws IOException
{
Utf8StringBuilder buffer = new Utf8StringBuilder();
String key = null;
String value = null;
int b;
int totalLength = 0;
while ((b = in.read()) >= 0)
synchronized (map)
{
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;
Utf8StringBuilder buffer = new Utf8StringBuilder();
String key = null;
String value = null;
case '=':
if (key != null)
{
int b;
int totalLength = 0;
while ((b = in.read()) >= 0)
{
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;
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);
if (key != null)
{
value = buffer.toReplacedString();
buffer.reset();
map.add(key, value);
}
else if (buffer.length() > 0)
{
map.add(buffer.toReplacedString(), "");
}
checkMaxKeys(map, maxKeys);
}
else if (buffer.length() > 0)
{
map.add(buffer.toReplacedString(), "");
}
checkMaxKeys(map, maxKeys);
}
public static void decodeUtf16To(InputStream in, MultiMap<String> map, int maxLength, int maxKeys) throws IOException
@ -615,74 +627,77 @@ public class UrlEncoded extends MultiMap<String> implements Cloneable
return;
}
String key = null;
String value = null;
int c;
int totalLength = 0;
try (ByteArrayOutputStream2 output = new ByteArrayOutputStream2())
synchronized (map)
{
int size = 0;
String key = null;
String value = null;
while ((c = in.read()) > 0)
int c;
int totalLength = 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);
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);
}
else if (size > 0)
{
map.add(output.toString(charset), "");
}
checkMaxKeys(map, maxKeys);
}
}

View File

@ -77,7 +77,7 @@ public abstract class AbstractLifeCycle implements LifeCycle
@Override
public final void start() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
try
{
@ -118,7 +118,7 @@ public abstract class AbstractLifeCycle implements LifeCycle
@Override
public final void stop() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
try
{

View File

@ -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 class AttributeContainerMap extends ContainerLifeCycle implements Attribu
@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 class AttributeContainerMap extends ContainerLifeCycle implements Attribu
@Override
public Object getAttribute(String name)
{
return _lock.runLocked(() -> _map.get(name));
try (AutoLock l = _lock.lock())
{
return _map.get(name);
}
}
@Override
public Enumeration<String> getAttributeNames()
{
return _lock.runLocked(() -> Collections.enumeration(getAttributeNameSet()));
try (AutoLock l = _lock.lock())
{
return Collections.enumeration(_map.keySet());
}
}
@Override
public Set<String> 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();

View File

@ -55,7 +55,7 @@ public class JarFileResource extends JarResource
@Override
public void close()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_exists = false;
_list = null;
@ -87,7 +87,7 @@ public class JarFileResource extends JarResource
@Override
protected boolean checkConnection()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
try
{
@ -110,7 +110,7 @@ public class JarFileResource extends JarResource
@Override
protected void newConnection() throws IOException
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
super.newConnection();
@ -265,7 +265,7 @@ public class JarFileResource extends JarResource
@Override
public String[] list()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (isDirectory() && _list == null)
{

View File

@ -57,7 +57,7 @@ public class JarResource extends URLResource
@Override
public void close()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_jarConnection = null;
super.close();
@ -67,7 +67,7 @@ public class JarResource extends URLResource
@Override
protected boolean checkConnection()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
super.checkConnection();
try

View File

@ -62,7 +62,7 @@ public class URLResource extends Resource
protected boolean checkConnection()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_connection == null)
{
@ -86,7 +86,7 @@ public class URLResource extends Resource
@Override
public void close()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (_in != null)
{
@ -114,7 +114,7 @@ public class URLResource extends Resource
{
try
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (checkConnection() && _in == null)
_in = _connection.getInputStream();
@ -219,7 +219,7 @@ public class URLResource extends Resource
*/
protected InputStream getInputStream(boolean resetConnection) throws IOException
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (!checkConnection())
throw new IOException("Invalid resource");

View File

@ -27,6 +27,7 @@ import java.util.stream.Collectors;
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 abstract class Credential implements Serializable
{
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 abstract class Credential implements Serializable
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 abstract class Credential implements Serializable
{
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)

View File

@ -214,7 +214,7 @@ public abstract class SslContextFactory extends AbstractLifeCycle implements Dum
protected void doStart() throws Exception
{
super.doStart();
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
load();
}
@ -438,7 +438,7 @@ public abstract class SslContextFactory extends AbstractLifeCycle implements Dum
@Override
protected void doStop() throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
unload();
}
@ -1041,7 +1041,7 @@ public abstract class SslContextFactory extends AbstractLifeCycle implements Dum
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 abstract class SslContextFactory extends AbstractLifeCycle implements Dum
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 abstract class SslContextFactory extends AbstractLifeCycle implements Dum
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 abstract class SslContextFactory extends AbstractLifeCycle implements Dum
public void reload(Consumer<SslContextFactory> consumer) throws Exception
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
consumer.accept(this);
unload();

View File

@ -64,7 +64,7 @@ public class RateStatistic
*/
public void reset()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_samples.clear();
_max = 0;
@ -91,7 +91,7 @@ public class RateStatistic
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 @@ public class RateStatistic
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 class RateStatistic
*/
public int getRate()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
update();
return _samples.size();
@ -139,7 +139,10 @@ public class RateStatistic
*/
public long getMax()
{
return _lock.runLocked(() -> _max);
try (AutoLock l = _lock.lock())
{
return _max;
}
}
/**
@ -148,7 +151,7 @@ public class RateStatistic
*/
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 class RateStatistic
*/
public long getCount()
{
return _lock.runLocked(() -> _count);
try (AutoLock l = _lock.lock())
{
return _count;
}
}
public String dump()
@ -173,7 +179,7 @@ public class RateStatistic
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 class RateStatistic
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}",

View File

@ -22,7 +22,6 @@ 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;
/**
* <p>Reentrant lock that can be used in a try-with-resources statement.</p>
@ -36,6 +35,8 @@ import java.util.function.Supplier;
*/
public class AutoLock implements AutoCloseable, Serializable
{
private static final long serialVersionUID = 3300696774541816341L;
private final ReentrantLock _lock = new ReentrantLock();
/**
@ -49,48 +50,6 @@ public class AutoLock implements AutoCloseable, Serializable
return this;
}
/**
* <p>Runs the given code with the lock held.</p>
* <p>This is equivalent to:</p>
* <pre>
* try (AutoLock ignored = lock())
* {
* code.run();
* }
* </pre>
*
* @param code the code to run with the lock held.
*/
public void runLocked(Runnable code)
{
try (AutoLock ignored = lock())
{
code.run();
}
}
/**
* <p>Returns the result of running the given code with the lock held.</p>
* <p>This is equivalent to:</p>
* <pre>
* try (AutoLock ignored = lock())
* {
* return code.get();
* }
* </pre>
*
* @param code the code to run with the lock held.
* @param <T> the result type
* @return the result of the code run
*/
public <T> T runLocked(Supplier<T> code)
{
try (AutoLock ignored = lock())
{
return code.get();
}
}
/**
* @see ReentrantLock#isHeldByCurrentThread()
* @return whether this lock is held by the current thread

View File

@ -277,9 +277,9 @@ public class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor
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 class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor
@Override
public void join() throws InterruptedException
{
try (AutoLock.WithCondition lock = _joinLock.lock())
try (AutoLock.WithCondition l = _joinLock.lock())
{
while (isRunning())
{
lock.await();
l.await();
}
}

View File

@ -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 @@ import org.slf4j.LoggerFactory;
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<LifeCycle> _lifeCycles = new CopyOnWriteArrayList<>();
private boolean _hooked;
private final List<LifeCycle> _lifeCycles = new CopyOnWriteArrayList<LifeCycle>();
/**
* Default constructor for the singleton
@ -55,7 +54,7 @@ public class ShutdownThread extends Thread
private void hook()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
if (!_hooked)
Runtime.getRuntime().addShutdownHook(this);
@ -70,7 +69,7 @@ public class ShutdownThread extends Thread
private void unhook()
{
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
_hooked = false;
Runtime.getRuntime().removeShutdownHook(this);
@ -83,53 +82,57 @@ public class ShutdownThread extends Thread
}
/**
* @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<LifeCycle> lifeCycles = INSTANCE._lock.runLocked(() -> new ArrayList<>(INSTANCE._lifeCycles));
for (LifeCycle lifeCycle : lifeCycles)
for (LifeCycle lifeCycle : _thread._lifeCycles)
{
try
{

View File

@ -99,7 +99,7 @@ public class EatWhatYouKill extends ContainerLifeCycle implements ExecutionStrat
public void dispatch()
{
boolean execute = false;
try (AutoLock ignored = _lock.lock())
try (AutoLock l = _lock.lock())
{
switch (_state)
{
@ -142,7 +142,7 @@ public class EatWhatYouKill extends ContainerLifeCycle implements ExecutionStrat
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 @@ public class EatWhatYouKill extends ContainerLifeCycle implements ExecutionStrat
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 @@ public class EatWhatYouKill extends ContainerLifeCycle implements ExecutionStrat
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 @@ public class EatWhatYouKill extends ContainerLifeCycle implements ExecutionStrat
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 @@ public class EatWhatYouKill extends ContainerLifeCycle implements ExecutionStrat
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 class EatWhatYouKill extends ContainerLifeCycle implements ExecutionStrat
@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 class EatWhatYouKill extends ContainerLifeCycle implements ExecutionStrat
@Override
public String toString()
{
return _lock.runLocked(this::toStringLocked);
try (AutoLock l = _lock.lock())
{
return toStringLocked();
}
}
public String toStringLocked()

View File

@ -74,49 +74,47 @@ public class Configurations extends AbstractList<Configuration> implements Dumpa
public static List<Configuration> 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)
catch (Throwable e)
{
LOG.warn("Unable to get known Configuration", e);
}
});
sort(__known);
if (LOG.isDebugEnabled())
{
LOG.warn("Unable to get known Configuration", e);
}
});
sort(__known);
if (LOG.isDebugEnabled())
{
for (Configuration c : __known)
{
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 class Configurations extends AbstractList<Configuration> implements Dumpa
{
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();

View File

@ -367,7 +367,7 @@ public class MetaData
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

View File

@ -34,13 +34,13 @@ public class ConfigurationsTest
@AfterEach
public void tearDown()
{
Configurations.clearKnown();
Configurations.cleanKnown();
}
@BeforeEach
public void setup()
{
Configurations.clearKnown();
Configurations.cleanKnown();
}
@Test

View File

@ -76,7 +76,7 @@ public class WebAppContextTest
@AfterEach
public void tearDown()
{
Configurations.clearKnown();
Configurations.cleanKnown();
}
@Test
@ -157,7 +157,7 @@ public class WebAppContextTest
@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 class WebAppContextTest
@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 class WebAppContextTest
@Test
public void testConfigurationInstances()
{
Configurations.clearKnown();
Configurations.cleanKnown();
Configuration[] configs = {new WebInfConfiguration()};
WebAppContext wac = new WebAppContext();
wac.setConfigurations(configs);

View File

@ -116,7 +116,7 @@ public class FrameFlusher extends IteratingCallback
List<Entry> failedEntries = null;
CloseStatus closeStatus = null;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (canEnqueue)
{
@ -188,7 +188,10 @@ public class FrameFlusher extends IteratingCallback
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 @@ public class FrameFlusher extends IteratingCallback
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 @@ public class FrameFlusher extends IteratingCallback
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 class FrameFlusher extends IteratingCallback
{
BufferUtil.clear(batchBuffer);
releaseAggregate();
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
failedEntries.addAll(queue);
queue.clear();

View File

@ -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");

View File

@ -70,7 +70,7 @@ public abstract class TransformingFlusher
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 abstract class TransformingFlusher
private void onFailure(Throwable t)
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (failure == null)
failure = t;
@ -97,7 +97,10 @@ public abstract class TransformingFlusher
private FrameEntry pollEntry()
{
return lock.runLocked(entries::poll);
try (AutoLock l = lock.lock())
{
return entries.poll();
}
}
private class Flusher extends IteratingCallback implements Callback

View File

@ -264,7 +264,7 @@ public class WebSocketConnection extends AbstractConnection implements Connectio
private void acquireNetworkBuffer()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (networkBuffer == null)
networkBuffer = newNetworkBuffer(getInputBufferSize());
@ -273,7 +273,7 @@ public class WebSocketConnection extends AbstractConnection implements Connectio
private void reacquireNetworkBuffer()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (networkBuffer == null)
throw new IllegalStateException();
@ -293,7 +293,7 @@ public class WebSocketConnection extends AbstractConnection implements Connectio
private void releaseNetworkBuffer()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (networkBuffer == null)
throw new IllegalStateException();
@ -328,7 +328,7 @@ public class WebSocketConnection extends AbstractConnection implements Connectio
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 class WebSocketConnection extends AbstractConnection implements Connectio
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 class WebSocketConnection extends AbstractConnection implements Connectio
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 class WebSocketConnection extends AbstractConnection implements Connectio
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 @@ public class WebSocketConnection extends AbstractConnection implements Connectio
{
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);

View File

@ -50,7 +50,7 @@ public class WebSocketSessionState
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 class WebSocketSessionState
public void onOpen()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
switch (_sessionState)
{
@ -82,7 +82,10 @@ public class WebSocketSessionState
private State getState()
{
return lock.runLocked(() -> _sessionState);
try (AutoLock l = lock.lock())
{
return _sessionState;
}
}
public boolean isClosed()
@ -104,12 +107,15 @@ public class WebSocketSessionState
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 class WebSocketSessionState
*/
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 class WebSocketSessionState
public boolean onEof()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
switch (_sessionState)
{
@ -177,7 +183,7 @@ public class WebSocketSessionState
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 class WebSocketSessionState
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());

View File

@ -62,11 +62,38 @@ import org.slf4j.LoggerFactory;
public class JavaxWebSocketFrameHandler implements FrameHandler
{
private final AutoLock lock = new AutoLock();
private final AtomicBoolean closeNotified = new AtomicBoolean();
private final Map<Byte, RegisteredMessageHandler> 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.
* <p>
* 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.
* </p>
* <p>
* Can be null if client side, or no named variables were configured on the server side.
* </p>
*/
/**
* The Map of path parameter values that arrived during the server side upgrade process.
* <p>
* 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.
* </p>
* <p>
* 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).
* </p>
* <p>
* 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.
* </p>
*/
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<Byte, RegisteredMessageHandler> messageHandlerMap = new HashMap<>();
private MessageSink textSink;
private MessageSink binarySink;
private MessageSink activeMessageSink;
@ -497,7 +525,7 @@ public class JavaxWebSocketFrameHandler implements FrameHandler
private <T> MessageSink registerMessageHandler(byte basicWebSocketMessageType, Class<T> 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 @@ public class JavaxWebSocketFrameHandler implements FrameHandler
public void removeMessageHandler(MessageHandler handler)
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
Optional<Map.Entry<Byte, RegisteredMessageHandler>> optionalEntry = messageHandlerMap.entrySet().stream()
.filter((entry) -> entry.getValue().getMessageHandler().equals(handler))

View File

@ -191,7 +191,7 @@ public class JettyWebSocketFrameHandler implements FrameHandler
@Override
public void onFrame(Frame frame, Callback callback)
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
switch (state)
{
@ -300,8 +300,11 @@ public class JettyWebSocketFrameHandler implements FrameHandler
@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 class JettyWebSocketFrameHandler implements FrameHandler
public void suspend()
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
switch (state)
{
@ -442,7 +445,7 @@ public class JettyWebSocketFrameHandler implements FrameHandler
{
boolean needDemand = false;
Runnable delayedFrame = null;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
switch (state)
{
@ -479,7 +482,7 @@ public class JettyWebSocketFrameHandler implements FrameHandler
private void demand()
{
boolean demand = false;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
switch (state)
{

View File

@ -59,7 +59,7 @@ public class MessageInputStream extends InputStream implements MessageSink
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 class MessageInputStream extends InputStream implements MessageSink
LOG.debug("close()");
ArrayList<Entry> entries = new ArrayList<>();
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (closed)
return;
@ -172,7 +172,7 @@ public class MessageInputStream extends InputStream implements MessageSink
private void succeedCurrentEntry()
{
Entry current;
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
current = currentEntry;
currentEntry = null;
@ -183,7 +183,7 @@ public class MessageInputStream extends InputStream implements MessageSink
private Entry getCurrentEntry() throws IOException
{
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
if (currentEntry != null)
return currentEntry;
@ -208,7 +208,7 @@ public class MessageInputStream extends InputStream implements MessageSink
throw new IOException(String.format("Read timeout: %,dms expired", timeoutMs));
}
try (AutoLock ignored = lock.lock())
try (AutoLock l = lock.lock())
{
currentEntry = result;
return currentEntry;

View File

@ -125,7 +125,7 @@ public class MessageOutputStream extends OutputStream
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 @@ public class MessageOutputStream extends OutputStream
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 class MessageOutputStream extends OutputStream
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);
}

View File

@ -250,7 +250,7 @@ public class XmlConfiguration
*/
public XmlConfiguration(Resource resource) throws SAXException, IOException
{
try (AutoLock ignored = PARSER.lock())
try (AutoLock l = PARSER.lock())
{
_location = resource;
try (InputStream inputStream = resource.getInputStream())

View File

@ -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<String, URL> _redirectMap = new HashMap<>();
private final Stack<ContentHandler> _observers = new Stack<>();
private Map<String, URL> _redirectMap = new HashMap<String, URL>();
private SAXParser _parser;
private Map<String, ContentHandler> _observerMap;
private Stack<ContentHandler> _observers = new Stack<ContentHandler>();
private String _xpath;
private Object _xpaths;
private String _dtd;
/**
* Construct
*/
public XmlParser()
{
SAXParserFactory factory = SAXParserFactory.newInstance();
@ -134,7 +137,12 @@ public class XmlParser
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 class XmlParser
*/
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 class XmlParser
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 class XmlParser
public void add(int i, Object o)
{
if (_list == null)
_list = new ArrayList<>();
_list = new ArrayList<Object>();
if (o instanceof String)
{
if (_lastString)

View File

@ -256,7 +256,7 @@ public class HttpTesterTest
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;

View File

@ -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 class DateCacheSimpleDateFormat
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 class DateCacheSimpleDateFormat
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 class DateCacheSimpleDateFormat
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 class DateCacheSimpleDateFormat
{
// 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 @@ public class DateCacheSimpleDateFormat
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)