Fixes #8532 - Review System.nanoTime() usages. (#8535)

* Fixes #8532 - Review System.nanoTime() usages.

Introduced o.e.j.util.NanoTime class to deal with nanoTimes.

Now NanoTime.now() should be used instead of System.nanoTime(),
and various <unit>[elapsed|since|until]() methods to calculate nanoTimes.

Furthermore, comparing 2 nanoTimes should be done via isBefore(),
rather than using the < operator, which is wrong as specified in
the System.nanoTime() javadocs.

Signed-off-by: Simone Bordet <simone.bordet@gmail.com>
This commit is contained in:
Simone Bordet 2022-09-06 09:30:02 +02:00 committed by GitHub
parent df2826f0c3
commit 77ad0189ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
114 changed files with 786 additions and 654 deletions

View File

@ -31,6 +31,7 @@ import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Utf8StringBuilder;
import org.eclipse.jetty.util.ajax.JSON;
@ -72,7 +73,7 @@ public class AsyncRestServlet extends AbstractRestServlet
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
long start = System.nanoTime();
long start = NanoTime.now();
// Do we have results yet?
@SuppressWarnings("unchecked")
@ -119,7 +120,7 @@ public class AsyncRestServlet extends AbstractRestServlet
// save timing info and return
request.setAttribute(START_ATTR, start);
request.setAttribute(DURATION_ATTR, System.nanoTime() - start);
request.setAttribute(DURATION_ATTR, NanoTime.since(start));
return;
}
@ -138,9 +139,9 @@ public class AsyncRestServlet extends AbstractRestServlet
long initial = (Long)request.getAttribute(DURATION_ATTR);
long start0 = (Long)request.getAttribute(START_ATTR);
long now = System.nanoTime();
long total = now - start0;
long generate = now - start;
long now = NanoTime.now();
long total = NanoTime.elapsed(start0, now);
long generate = NanoTime.elapsed(start, now);
long thread = initial + generate;
out.print("<b>Asynchronous: " + sanitize(request.getParameter(ITEMS_PARAM)) + "</b><br/>");

View File

@ -26,6 +26,7 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.ajax.JSON;
/**
@ -36,7 +37,7 @@ public class SerialRestServlet extends AbstractRestServlet
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
final long start = System.nanoTime();
long start = NanoTime.now();
String[] keywords = sanitize(request.getParameter(ITEMS_PARAM)).split(",");
Queue<Map<String, Object>> results = new LinkedList<>();
@ -72,8 +73,7 @@ public class SerialRestServlet extends AbstractRestServlet
out.println(STYLE);
out.println("</head><body><small>");
long now = System.nanoTime();
long total = now - start;
long total = NanoTime.since(start);
out.print("<b>Blocking: " + sanitize(request.getParameter(ITEMS_PARAM)) + "</b><br/>");
out.print("Total Time: " + ms(total) + "ms<br/>");

View File

@ -21,6 +21,7 @@ import java.nio.file.Path;
import java.time.Duration;
import org.eclipse.jetty.util.IteratingCallback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.StatusCode;
@ -256,7 +257,7 @@ public class WebSocketDocs
remote.sendBytes(bytes);
// Send a PING frame to the remote peer.
remote.sendPing(ByteBuffer.allocate(8).putLong(System.nanoTime()).flip());
remote.sendPing(ByteBuffer.allocate(8).putLong(NanoTime.now()).flip());
}
catch (IOException x)
{
@ -425,7 +426,7 @@ public class WebSocketDocs
public void onWebSocketConnect(Session session)
{
// Send to the remote peer the local nanoTime.
ByteBuffer buffer = ByteBuffer.allocate(8).putLong(System.nanoTime()).flip();
ByteBuffer buffer = ByteBuffer.allocate(8).putLong(NanoTime.now()).flip();
session.getRemote().sendPing(buffer, WriteCallback.NOOP);
}
@ -436,7 +437,7 @@ public class WebSocketDocs
long start = payload.getLong();
// Calculate the round-trip time.
long roundTrip = System.nanoTime() - start;
long roundTrip = NanoTime.since(start);
}
}
// end::pingPongListener[]

View File

@ -72,6 +72,7 @@ import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.eclipse.jetty.unixdomain.server.UnixDomainServerConnector;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.eclipse.jetty.util.ssl.SslContextFactory;
@ -126,14 +127,14 @@ public class HTTPServerDocs
@Override
public void onRequestBegin(Request request)
{
times.put(request, System.nanoTime());
times.put(request, NanoTime.now());
}
@Override
public void onComplete(Request request)
{
long begin = times.remove(request);
long elapsed = System.nanoTime() - begin;
long elapsed = NanoTime.since(begin);
System.getLogger("timing").log(INFO, "Request {0} took {1} ns", request, elapsed);
}
}

View File

@ -46,6 +46,7 @@ import org.eclipse.jetty.servlet.Source.Origin;
import org.eclipse.jetty.util.JavaVersion;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.ProcessorUtils;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.TypeUtil;
@ -101,38 +102,26 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
/**
* TimeStatistic
*
* Simple class to capture elapsed time of an operation.
*/
public class TimeStatistic
public static class TimeStatistic
{
public long _start = 0;
public long _end = 0;
public void start()
{
_start = System.nanoTime();
_start = NanoTime.now();
}
public void end()
{
_end = System.nanoTime();
_end = NanoTime.now();
}
public long getStart()
public long getElapsedNanos()
{
return _start;
}
public long getEnd()
{
return _end;
}
public long getElapsed()
{
return (_end > _start ? (_end - _start) : 0);
return NanoTime.elapsed(_start, _end);
}
}
@ -531,7 +520,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
//scan non-excluded, non medatadata-complete jars in web-inf lib
parseWebInfLib(context, parser);
long start = System.nanoTime();
long start = NanoTime.now();
//execute scan, either effectively synchronously (1 thread only), or asynchronously (limited by number of processors available)
final Semaphore task_limit = (isUseMultiThreading(context) ? new Semaphore(ProcessorUtils.availableProcessors()) : new Semaphore(1));
@ -564,15 +553,14 @@ public class AnnotationConfiguration extends AbstractConfiguration
}
boolean timeout = !latch.await(getMaxScanWait(context), TimeUnit.SECONDS);
long elapsedMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
long elapsedMs = NanoTime.millisSince(start);
if (LOG.isDebugEnabled())
{
LOG.debug("Annotation scanning elapsed time={}ms", elapsedMs);
for (ParserTask p : _parserTasks)
{
LOG.debug("Scanned {} in {}ms", p.getResource(), TimeUnit.MILLISECONDS.convert(p.getStatistic().getElapsed(), TimeUnit.NANOSECONDS));
LOG.debug("Scanned {} in {}ms", p.getResource(), TimeUnit.NANOSECONDS.toMillis(p.getStatistic().getElapsedNanos()));
}
LOG.debug("Scanned {} container path jars, {} WEB-INF/lib jars, {} WEB-INF/classes dirs in {}ms for context {}",
@ -870,9 +858,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
ArrayList<ServletContainerInitializer> nonExcludedInitializers = new ArrayList<ServletContainerInitializer>();
//We use the ServiceLoader mechanism to find the ServletContainerInitializer classes to inspect
long start = 0;
if (LOG.isDebugEnabled())
start = System.nanoTime();
long start = NanoTime.now();
List<ServletContainerInitializer> scis = TypeUtil.serviceProviderStream(ServiceLoader.load(ServletContainerInitializer.class)).flatMap(provider ->
{
try
@ -891,7 +877,7 @@ public class AnnotationConfiguration extends AbstractConfiguration
}).collect(Collectors.toList());
if (LOG.isDebugEnabled())
LOG.debug("Service loaders found in {}ms", (TimeUnit.MILLISECONDS.convert((System.nanoTime() - start), TimeUnit.NANOSECONDS)));
LOG.debug("Service loaders found in {}ms", NanoTime.millisSince(start));
Map<ServletContainerInitializer, Resource> sciResourceMap = new HashMap<>();
ServletContainerInitializerOrdering initializerOrdering = getInitializerOrdering(context);

View File

@ -29,6 +29,7 @@ import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.util.Attachable;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Pool;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
@ -577,7 +578,7 @@ public abstract class AbstractConnectionPool extends ContainerLifeCycle implemen
private static class EntryHolder
{
private final Pool<Connection>.Entry entry;
private final long creationTimestamp = System.nanoTime();
private final long creationNanoTime = NanoTime.now();
private EntryHolder(Pool<Connection>.Entry entry)
{
@ -586,7 +587,7 @@ public abstract class AbstractConnectionPool extends ContainerLifeCycle implemen
private boolean isExpired(long timeoutNanos)
{
return System.nanoTime() - creationTimestamp >= timeoutNanos;
return NanoTime.since(creationNanoTime) >= timeoutNanos;
}
}
}

View File

@ -35,6 +35,7 @@ import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.QuotedCSV;
import org.eclipse.jetty.util.NanoTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -215,10 +216,10 @@ public abstract class AuthenticationProtocolHandler implements ProtocolHandler
// Adjust the timeout of the new request, taking into account the
// timeout of the previous request and the time already elapsed.
long timeoutAt = request.getTimeoutAt();
if (timeoutAt < Long.MAX_VALUE)
long timeoutNanoTime = request.getTimeoutNanoTime();
if (timeoutNanoTime < Long.MAX_VALUE)
{
long newTimeout = timeoutAt - System.nanoTime();
long newTimeout = NanoTime.until(timeoutNanoTime);
if (newTimeout > 0)
{
newRequest.timeout(newTimeout, TimeUnit.NANOSECONDS);

View File

@ -19,7 +19,6 @@ import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.client.api.Authentication;
@ -34,6 +33,7 @@ import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.io.CyclicTimeouts;
import org.eclipse.jetty.util.Attachable;
import org.eclipse.jetty.util.HttpCookieStore;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.AutoLock;
import org.eclipse.jetty.util.thread.Scheduler;
import org.slf4j.Logger;
@ -48,13 +48,13 @@ public abstract class HttpConnection implements IConnection, Attachable
private final RequestTimeouts requestTimeouts;
private Object attachment;
private int idleTimeoutGuard;
private long idleTimeoutStamp;
private long idleTimeoutNanoTime;
protected HttpConnection(HttpDestination destination)
{
this.destination = destination;
this.requestTimeouts = new RequestTimeouts(destination.getHttpClient().getScheduler());
this.idleTimeoutStamp = System.nanoTime();
this.idleTimeoutNanoTime = NanoTime.now();
}
public HttpClient getHttpClient()
@ -121,7 +121,7 @@ public abstract class HttpConnection implements IConnection, Attachable
try (AutoLock l = lock.lock())
{
--idleTimeoutGuard;
idleTimeoutStamp = System.nanoTime();
idleTimeoutNanoTime = NanoTime.now();
}
return result;
@ -267,7 +267,7 @@ public abstract class HttpConnection implements IConnection, Attachable
{
if (idleTimeoutGuard == 0)
{
long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - idleTimeoutStamp);
long elapsed = NanoTime.millisSince(idleTimeoutNanoTime);
boolean idle = elapsed > idleTimeout / 2;
if (idle)
idleTimeoutGuard = -1;

View File

@ -21,7 +21,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.client.api.Connection;
@ -35,6 +34,7 @@ import org.eclipse.jetty.io.CyclicTimeouts;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.HostPort;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ -66,7 +66,7 @@ public abstract class HttpDestination extends ContainerLifeCycle implements Dest
private final AutoLock staleLock = new AutoLock();
private ConnectionPool connectionPool;
private boolean stale;
private long activeNanos;
private long activeNanoTime;
public HttpDestination(HttpClient client, Origin origin, boolean intrinsicallySecure)
{
@ -116,7 +116,7 @@ public abstract class HttpDestination extends ContainerLifeCycle implements Dest
{
boolean stale = this.stale;
if (!stale)
this.activeNanos = System.nanoTime();
this.activeNanoTime = NanoTime.now();
if (LOG.isDebugEnabled())
LOG.debug("Stale check done with result {} on {}", stale, this);
return stale;
@ -134,9 +134,9 @@ public abstract class HttpDestination extends ContainerLifeCycle implements Dest
boolean stale = exchanges.isEmpty() && connectionPool.isEmpty();
if (!stale)
{
this.activeNanos = System.nanoTime();
this.activeNanoTime = NanoTime.now();
}
else if (isStaleDelayExpired())
else if (NanoTime.millisSince(activeNanoTime) >= getHttpClient().getDestinationIdleTimeout())
{
this.stale = true;
remove = true;
@ -152,13 +152,6 @@ public abstract class HttpDestination extends ContainerLifeCycle implements Dest
return remove;
}
private boolean isStaleDelayExpired()
{
assert staleLock.isHeldByCurrentThread();
long destinationIdleTimeout = TimeUnit.MILLISECONDS.toNanos(getHttpClient().getDestinationIdleTimeout());
return System.nanoTime() - activeNanos >= destinationIdleTimeout;
}
@Override
protected void doStart() throws Exception
{
@ -555,7 +548,7 @@ public abstract class HttpDestination extends ContainerLifeCycle implements Dest
return -1;
try (AutoLock l = staleLock.lock())
{
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - activeNanos);
return NanoTime.millisSince(activeNanoTime);
}
}

View File

@ -93,7 +93,7 @@ public class HttpExchange implements CyclicTimeouts.Expirable
@Override
public long getExpireNanoTime()
{
return request.getTimeoutAt();
return request.getTimeoutNanoTime();
}
/**

View File

@ -29,6 +29,7 @@ import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.BufferingResponseListener;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.util.NanoTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -311,10 +312,10 @@ public class HttpRedirector
// Adjust the timeout of the new request, taking into account the
// timeout of the previous request and the time already elapsed.
long timeoutAt = httpRequest.getTimeoutAt();
if (timeoutAt < Long.MAX_VALUE)
long timeoutNanoTime = httpRequest.getTimeoutNanoTime();
if (timeoutNanoTime < Long.MAX_VALUE)
{
long newTimeout = timeoutAt - System.nanoTime();
long newTimeout = NanoTime.until(timeoutNanoTime);
if (newTimeout > 0)
{
redirect.timeout(newTimeout, TimeUnit.NANOSECONDS);

View File

@ -55,6 +55,7 @@ import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.Fields;
import org.eclipse.jetty.util.NanoTime;
public class HttpRequest implements Request
{
@ -77,7 +78,7 @@ public class HttpRequest implements Request
private boolean versionExplicit;
private long idleTimeout = -1;
private long timeout;
private long timeoutAt = Long.MAX_VALUE;
private long timeoutNanoTime = Long.MAX_VALUE;
private Content content;
private boolean followRedirects;
private List<HttpCookie> cookies;
@ -823,16 +824,16 @@ public class HttpRequest implements Request
{
long timeout = getTimeout();
if (timeout > 0)
timeoutAt = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout);
timeoutNanoTime = NanoTime.now() + TimeUnit.MILLISECONDS.toNanos(timeout);
}
/**
* @return The nanoTime at which the timeout expires or {@link Long#MAX_VALUE} if there is no timeout.
* @see #timeout(long, TimeUnit)
*/
long getTimeoutAt()
long getTimeoutNanoTime()
{
return timeoutAt;
return timeoutNanoTime;
}
protected List<Response.ResponseListener> getResponseListeners()

View File

@ -22,6 +22,7 @@ import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.io.CyclicTimeout;
import org.eclipse.jetty.io.CyclicTimeouts;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -67,7 +68,7 @@ public class TimeoutCompleteListener extends CyclicTimeout implements Response.C
{
if (requestTimeout.compareAndSet(null, request))
{
long delay = Math.max(0, timeoutAt - System.nanoTime());
long delay = Math.max(0, NanoTime.until(timeoutAt));
if (LOG.isDebugEnabled())
LOG.debug("Scheduling timeout in {} ms for {} on {}", TimeUnit.NANOSECONDS.toMillis(delay), request, this);
schedule(delay, TimeUnit.NANOSECONDS);

View File

@ -21,6 +21,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.component.DumpableCollection;
@ -120,7 +121,7 @@ public class ValidatingConnectionPool extends DuplexConnectionPool
private class Holder implements Runnable
{
private final long timestamp = System.nanoTime();
private final long creationNanoTime = NanoTime.now();
private final AtomicBoolean done = new AtomicBoolean();
private final Connection connection;
public Scheduler.Task task;
@ -161,7 +162,7 @@ public class ValidatingConnectionPool extends DuplexConnectionPool
{
return String.format("%s[validationLeft=%dms]",
connection,
timeout - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timestamp)
timeout - NanoTime.millisSince(creationNanoTime)
);
}
}

View File

@ -33,6 +33,7 @@ import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -99,7 +100,7 @@ public class MultiPartContentProvider extends AbstractTypedContentProvider imple
StringBuilder builder = new StringBuilder("JettyHttpClientBoundary");
builder.append(Long.toString(System.identityHashCode(builder), 36));
builder.append(Long.toString(System.identityHashCode(Thread.currentThread()), 36));
builder.append(Long.toString(System.nanoTime(), 36));
builder.append(Long.toString(NanoTime.now(), 36));
return builder.toString();
}

View File

@ -44,6 +44,7 @@ import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.SocketAddressResolver;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
@ -186,13 +187,12 @@ public class ConnectionPoolTest
private void run(CountDownLatch latch, int iterations, List<Throwable> failures)
{
long begin = System.nanoTime();
long begin = NanoTime.now();
for (int i = 0; i < iterations; ++i)
{
test(failures);
}
long end = System.nanoTime();
long elapsed = TimeUnit.NANOSECONDS.toMillis(end - begin);
long elapsed = NanoTime.millisSince(begin);
System.err.printf("%d requests in %d ms, %.3f req/s%n", iterations, elapsed, elapsed > 0 ? iterations * 1000D / elapsed : -1D);
latch.countDown();
}

View File

@ -26,6 +26,7 @@ import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.util.NanoTime;
import org.hamcrest.Matchers;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
@ -350,8 +351,8 @@ public class DuplexHttpDestinationTest extends AbstractHttpClientServerTest
private Connection await(Supplier<Connection> supplier, long time, TimeUnit unit) throws InterruptedException
{
long start = System.nanoTime();
while (unit.toNanos(time) > System.nanoTime() - start)
long start = NanoTime.now();
while (NanoTime.since(start) < unit.toNanos(time))
{
Connection connection = supplier.get();
if (connection != null)

View File

@ -86,6 +86,7 @@ import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.FuturePromise;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.SocketAddressResolver;
import org.hamcrest.Matchers;
@ -127,9 +128,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
HttpDestination destination = (HttpDestination)client.resolveDestination(request);
DuplexConnectionPool connectionPool = (DuplexConnectionPool)destination.getConnectionPool();
long start = System.nanoTime();
long start = NanoTime.now();
HttpConnectionOverHTTP connection = null;
while (connection == null && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start) < 5)
while (connection == null && NanoTime.secondsSince(start) < 5)
{
connection = (HttpConnectionOverHTTP)connectionPool.getIdleConnections().peek();
TimeUnit.MILLISECONDS.sleep(10);
@ -611,7 +612,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
.file(file)
.onRequestSuccess(request ->
{
requestTime.set(System.nanoTime());
requestTime.set(NanoTime.now());
latch.countDown();
})
.send(new Response.Listener.Adapter()
@ -619,22 +620,22 @@ public class HttpClientTest extends AbstractHttpClientServerTest
@Override
public void onSuccess(Response response)
{
responseTime.set(System.nanoTime());
responseTime.set(NanoTime.now());
latch.countDown();
}
@Override
public void onComplete(Result result)
{
exchangeTime.set(System.nanoTime());
exchangeTime.set(NanoTime.now());
latch.countDown();
}
});
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertTrue(requestTime.get() <= exchangeTime.get());
assertTrue(responseTime.get() <= exchangeTime.get());
assertTrue(NanoTime.isBeforeOrSame(requestTime.get(), exchangeTime.get()));
assertTrue(NanoTime.isBeforeOrSame(responseTime.get(), exchangeTime.get()));
// Give some time to the server to consume the request content
// This is just to avoid exception traces in the test output

View File

@ -33,6 +33,7 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.jupiter.api.Test;
@ -67,12 +68,7 @@ public class HttpClientUploadDuringServerShutdownTest
int read = input.read(buffer);
if (read < 0)
break;
long now = System.nanoTime();
long sleep = TimeUnit.MICROSECONDS.toNanos(1);
while (System.nanoTime() < now + sleep)
{
// Wait.
}
NanoTime.spinWait(TimeUnit.MICROSECONDS.toNanos(1));
}
}
});

View File

@ -18,6 +18,7 @@ import java.util.Locale;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
@ -113,7 +114,7 @@ public class HttpCookie
_secure = secure;
_comment = comment;
_version = version;
_expiration = maxAge < 0 ? -1 : System.nanoTime() + TimeUnit.SECONDS.toNanos(maxAge);
_expiration = maxAge < 0 ? -1 : NanoTime.now() + TimeUnit.SECONDS.toNanos(maxAge);
_sameSite = sameSite;
}
@ -134,7 +135,7 @@ public class HttpCookie
_secure = cookie.getSecure();
_comment = cookie.getComment();
_version = cookie.getVersion();
_expiration = _maxAge < 0 ? -1 : System.nanoTime() + TimeUnit.SECONDS.toNanos(_maxAge);
_expiration = _maxAge < 0 ? -1 : NanoTime.now() + TimeUnit.SECONDS.toNanos(_maxAge);
// support for SameSite values has not yet been added to java.net.HttpCookie
_sameSite = getSameSiteFromComment(cookie.getComment());
}
@ -225,7 +226,7 @@ public class HttpCookie
*/
public boolean isExpired(long timeNanos)
{
return _expiration >= 0 && timeNanos >= _expiration;
return _expiration != -1 && NanoTime.isBefore(_expiration, timeNanos);
}
/**

View File

@ -26,6 +26,7 @@ import org.eclipse.jetty.http2.api.Stream;
import org.eclipse.jetty.http2.api.server.ServerSessionListener;
import org.eclipse.jetty.http2.frames.HeadersFrame;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Promise;
import org.junit.jupiter.api.Test;
@ -116,14 +117,12 @@ public class SessionFailureTest extends AbstractTest
assertTrue(writeLatch.await(5, TimeUnit.SECONDS));
assertTrue(serverFailureLatch.await(5, TimeUnit.SECONDS));
assertTrue(clientFailureLatch.await(5, TimeUnit.SECONDS));
long start = System.nanoTime();
long now = System.nanoTime();
long start = NanoTime.now();
while (((HTTP2Session)session).getEndPoint().isOpen())
{
assertThat(TimeUnit.NANOSECONDS.toSeconds(now - start), lessThanOrEqualTo(5L));
assertThat(NanoTime.secondsSince(start), lessThanOrEqualTo(5L));
Thread.sleep(10);
now = System.nanoTime();
}
}
}

View File

@ -41,6 +41,7 @@ import org.eclipse.jetty.util.ByteArrayOutputStream2;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.FuturePromise;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.Scheduler;
import org.hamcrest.Matchers;
@ -104,7 +105,7 @@ public class SmallThreadPoolLoadTest extends AbstractTest
}, iterations * factor, TimeUnit.MILLISECONDS);
long successes = 0;
long begin = System.nanoTime();
long begin = NanoTime.now();
for (int i = 0; i < iterations; ++i)
{
boolean success = test(session, latch);
@ -113,10 +114,9 @@ public class SmallThreadPoolLoadTest extends AbstractTest
}
assertTrue(latch.await(iterations, TimeUnit.SECONDS));
long end = System.nanoTime();
assertThat(successes, Matchers.greaterThan(0L));
task.cancel();
long elapsed = TimeUnit.NANOSECONDS.toMillis(end - begin);
long elapsed = NanoTime.millisSince(begin);
logger.info("{} requests in {} ms, {}/{} success/failure, {} req/s",
iterations, elapsed,
successes, iterations - successes,

View File

@ -84,6 +84,7 @@ import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.util.FuturePromise;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
@ -1101,11 +1102,10 @@ public class StreamResetTest extends AbstractTest
private void waitUntilTCPCongested(WriteFlusher flusher) throws TimeoutException, InterruptedException
{
long start = System.nanoTime();
long start = NanoTime.now();
while (!flusher.isPending())
{
long elapsed = System.nanoTime() - start;
if (TimeUnit.NANOSECONDS.toSeconds(elapsed) > 15)
if (NanoTime.secondsSince(start) > 15)
throw new TimeoutException();
Thread.sleep(100);
}

View File

@ -21,6 +21,7 @@ import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.http2.api.Stream;
import org.eclipse.jetty.http2.frames.WindowUpdateFrame;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
@ -180,21 +181,21 @@ public abstract class AbstractFlowControlStrategy implements FlowControlStrategy
protected void onSessionStalled(ISession session)
{
sessionStall.set(System.nanoTime());
sessionStall.set(NanoTime.now());
if (LOG.isDebugEnabled())
LOG.debug("Session stalled {}", session);
}
protected void onStreamStalled(IStream stream)
{
streamsStalls.put(stream, System.nanoTime());
streamsStalls.put(stream, NanoTime.now());
if (LOG.isDebugEnabled())
LOG.debug("Stream stalled {}", stream);
}
protected void onSessionUnstalled(ISession session)
{
long stallTime = System.nanoTime() - sessionStall.getAndSet(0);
long stallTime = NanoTime.since(sessionStall.getAndSet(0));
sessionStallTime.addAndGet(stallTime);
if (LOG.isDebugEnabled())
LOG.debug("Session unstalled after {} ms {}", TimeUnit.NANOSECONDS.toMillis(stallTime), session);
@ -205,7 +206,7 @@ public abstract class AbstractFlowControlStrategy implements FlowControlStrategy
Long time = streamsStalls.remove(stream);
if (time != null)
{
long stallTime = System.nanoTime() - time;
long stallTime = NanoTime.since(time);
streamsStallTime.addAndGet(stallTime);
if (LOG.isDebugEnabled())
LOG.debug("Stream unstalled after {} ms {}", TimeUnit.NANOSECONDS.toMillis(stallTime), stream);
@ -218,7 +219,7 @@ public abstract class AbstractFlowControlStrategy implements FlowControlStrategy
long pastStallTime = sessionStallTime.get();
long currentStallTime = sessionStall.get();
if (currentStallTime != 0)
currentStallTime = System.nanoTime() - currentStallTime;
currentStallTime = NanoTime.since(currentStallTime);
return TimeUnit.NANOSECONDS.toMillis(pastStallTime + currentStallTime);
}
@ -226,8 +227,8 @@ public abstract class AbstractFlowControlStrategy implements FlowControlStrategy
public long getStreamsStallTime()
{
long pastStallTime = streamsStallTime.get();
long now = System.nanoTime();
long currentStallTime = streamsStalls.values().stream().reduce(0L, (result, time) -> now - time);
long now = NanoTime.now();
long currentStallTime = streamsStalls.values().stream().reduce(0L, (result, time) -> NanoTime.elapsed(time, now));
return TimeUnit.NANOSECONDS.toMillis(pastStallTime + currentStallTime);
}

View File

@ -29,7 +29,6 @@ import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@ -66,6 +65,7 @@ import org.eclipse.jetty.util.Atomics;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.CountingCallback;
import org.eclipse.jetty.util.MathUtils;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ -1008,7 +1008,7 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio
private void notIdle()
{
streamsState.idleTime = System.nanoTime();
streamsState.idleNanoTime = NanoTime.now();
}
@Override
@ -1516,7 +1516,7 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio
private final Queue<Slot> slots = new ArrayDeque<>();
// Must be incremented with the lock held.
private final AtomicLong streamCount = new AtomicLong();
private long idleTime = System.nanoTime();
private long idleNanoTime = NanoTime.now();
private CloseState closed = CloseState.NOT_CLOSED;
private Runnable zeroStreamsAction;
private GoAwayFrame goAwayRecv;
@ -1872,7 +1872,7 @@ public abstract class HTTP2Session extends ContainerLifeCycle implements ISessio
{
case NOT_CLOSED:
{
long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - idleTime);
long elapsed = NanoTime.millisSince(idleNanoTime);
if (elapsed < endPoint.getIdleTimeout())
return false;
notify = true;

View File

@ -41,6 +41,7 @@ import org.eclipse.jetty.io.CyclicTimeouts;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.MathUtils;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.thread.AutoLock;
@ -59,7 +60,7 @@ public class HTTP2Stream implements IStream, Callback, Dumpable, CyclicTimeouts.
private final AtomicReference<CloseState> closeState = new AtomicReference<>(CloseState.NOT_CLOSED);
private final AtomicInteger sendWindow = new AtomicInteger();
private final AtomicInteger recvWindow = new AtomicInteger();
private final long timeStamp = System.nanoTime();
private final long creationNanoTime = NanoTime.now();
private final ISession session;
private final int streamId;
private final MetaData.Request request;
@ -294,7 +295,7 @@ public class HTTP2Stream implements IStream, Callback, Dumpable, CyclicTimeouts.
{
long idleTimeout = getIdleTimeout();
if (idleTimeout > 0)
expireNanoTime = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(idleTimeout);
expireNanoTime = NanoTime.now() + TimeUnit.MILLISECONDS.toNanos(idleTimeout);
}
@Override
@ -931,7 +932,7 @@ public class HTTP2Stream implements IStream, Callback, Dumpable, CyclicTimeouts.
localReset,
remoteReset,
closeState,
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timeStamp),
NanoTime.millisSince(creationNanoTime),
attachment);
}

View File

@ -19,6 +19,7 @@ import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.util.NanoTime;
/**
* <p>An implementation of {@link RateControl} that limits the number of
@ -65,13 +66,13 @@ public class WindowRateControl implements RateControl
@Override
public boolean onEvent(Object event)
{
long now = System.nanoTime();
long now = NanoTime.now();
while (true)
{
Long time = events.peek();
if (time == null)
break;
if (now < time)
if (NanoTime.isBefore(now, time))
break;
if (events.remove(time))
size.decrementAndGet();

View File

@ -24,6 +24,7 @@ import org.eclipse.jetty.http2.generator.PingGenerator;
import org.eclipse.jetty.http2.parser.Parser;
import org.eclipse.jetty.io.ByteBufferPool;
import org.eclipse.jetty.io.MappedByteBufferPool;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
@ -133,7 +134,7 @@ public class PingGenerateParseTest
parser.init(UnaryOperator.identity());
ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
PingFrame ping = new PingFrame(System.nanoTime(), true);
PingFrame ping = new PingFrame(NanoTime.now(), true);
generator.generate(lease, ping);
for (ByteBuffer buffer : lease.getByteBuffers())

View File

@ -14,7 +14,6 @@
package org.eclipse.jetty.http2.hpack;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.http.DateGenerator;
import org.eclipse.jetty.http.HttpField;
@ -38,7 +37,7 @@ public class HpackTest
{
static final HttpField ServerJetty = new PreEncodedHttpField(HttpHeader.SERVER, "jetty");
static final HttpField XPowerJetty = new PreEncodedHttpField(HttpHeader.X_POWERED_BY, "jetty");
static final HttpField Date = new PreEncodedHttpField(HttpHeader.DATE, DateGenerator.formatDate(TimeUnit.NANOSECONDS.toMillis(System.nanoTime())));
static final HttpField Date = new PreEncodedHttpField(HttpHeader.DATE, DateGenerator.formatDate(System.currentTimeMillis()));
@Test
public void encodeDecodeResponseTest() throws Exception

View File

@ -63,6 +63,7 @@ import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
@ -503,11 +504,10 @@ public class MaxConcurrentStreamsTest extends AbstractTest
// Wait until TCP congested.
assertTrue(clientEndPointLatch.await(5, TimeUnit.SECONDS));
AbstractEndPoint clientEndPoint = clientEndPointRef.get();
long start = System.nanoTime();
long start = NanoTime.now();
while (!clientEndPoint.getWriteFlusher().isPending())
{
long elapsed = System.nanoTime() - start;
assertThat(TimeUnit.NANOSECONDS.toSeconds(elapsed), Matchers.lessThan(15L));
assertThat(NanoTime.secondsSince(start), Matchers.lessThan(15L));
Thread.sleep(100);
}
// Wait for the selector to update the SelectionKey to OP_WRITE.

View File

@ -26,6 +26,7 @@ import org.eclipse.jetty.io.CyclicTimeouts;
import org.eclipse.jetty.quic.common.QuicStreamEndPoint;
import org.eclipse.jetty.util.Attachable;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Promise;
import org.eclipse.jetty.util.thread.Invocable;
import org.slf4j.Logger;
@ -109,7 +110,7 @@ public abstract class HTTP3Stream implements Stream, CyclicTimeouts.Expirable, A
{
long idleTimeout = getIdleTimeout();
if (idleTimeout > 0)
expireNanoTime = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(idleTimeout);
expireNanoTime = NanoTime.now() + TimeUnit.MILLISECONDS.toNanos(idleTimeout);
}
boolean onIdleTimeout(TimeoutException timeout)
@ -308,7 +309,7 @@ public abstract class HTTP3Stream implements Stream, CyclicTimeouts.Expirable, A
hashCode(),
getId(),
hasDemand(),
TimeUnit.NANOSECONDS.toMillis(expireNanoTime - System.nanoTime()),
NanoTime.millisSince(expireNanoTime),
getSession()
);
}

View File

@ -23,6 +23,7 @@ import java.util.function.Consumer;
import java.util.function.IntConsumer;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
@ -176,7 +177,7 @@ abstract class AbstractByteBufferPool implements ByteBufferPool
private final int _capacity;
private final int _maxSize;
private final AtomicInteger _size;
private final AtomicLong _lastUpdate = new AtomicLong(System.nanoTime());
private final AtomicLong _lastUpdate = new AtomicLong(NanoTime.now());
private final IntConsumer _memoryFunction;
@Deprecated
@ -223,7 +224,7 @@ abstract class AbstractByteBufferPool implements ByteBufferPool
void resetUpdateTime()
{
_lastUpdate.lazySet(System.nanoTime());
_lastUpdate.lazySet(NanoTime.now());
}
public void clear()

View File

@ -22,6 +22,7 @@ import java.util.Objects;
import java.util.stream.Collectors;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.component.Dumpable;
@ -208,10 +209,10 @@ public class ArrayByteBufferPool extends AbstractByteBufferPool implements Dumpa
Bucket bucket = buckets[i];
if (bucket.isEmpty())
continue;
long lastUpdate = bucket.getLastUpdate();
if (lastUpdate < oldest)
long lastUpdateNanoTime = bucket.getLastUpdate();
if (oldest == Long.MAX_VALUE || NanoTime.isBefore(lastUpdateNanoTime, oldest))
{
oldest = lastUpdate;
oldest = lastUpdateNanoTime;
index = i;
}
}

View File

@ -21,6 +21,7 @@ import java.util.function.Consumer;
import java.util.function.Function;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Pool;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ -353,7 +354,7 @@ public class ArrayRetainableByteBufferPool implements RetainableByteBufferPool,
{
if (LOG.isDebugEnabled())
LOG.debug("evicting {} bytes from {} pools", excess, (direct ? "direct" : "heap"));
long now = System.nanoTime();
long now = NanoTime.now();
long totalClearedCapacity = 0L;
RetainedBucket[] buckets = direct ? _direct : _indirect;
@ -413,8 +414,8 @@ public class ArrayRetainableByteBufferPool implements RetainableByteBufferPool,
{
if (oldestEntry != null)
{
long entryAge = now - entry.getPooled().getLastUpdate();
if (entryAge > now - oldestEntry.getPooled().getLastUpdate())
long entryAge = NanoTime.elapsed(entry.getPooled().getLastUpdate(), now);
if (entryAge > NanoTime.elapsed(oldestEntry.getPooled().getLastUpdate(), now))
oldestEntry = entry;
}
else

View File

@ -16,6 +16,7 @@ package org.eclipse.jetty.io;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.component.Destroyable;
import org.eclipse.jetty.util.thread.Scheduler;
import org.slf4j.Logger;
@ -91,7 +92,7 @@ public abstract class CyclicTimeout implements Destroyable
*/
public boolean schedule(long delay, TimeUnit units)
{
long now = System.nanoTime();
long now = NanoTime.now();
long newTimeoutAt = now + units.toNanos(delay);
Wakeup newWakeup = null;
@ -103,7 +104,7 @@ public abstract class CyclicTimeout implements Destroyable
// Is the current wakeup good to use? ie before our timeout time?
Wakeup wakeup = timeout._wakeup;
if (wakeup == null || wakeup._at > newTimeoutAt)
if (wakeup == null || NanoTime.isBefore(newTimeoutAt, wakeup._at))
// No, we need an earlier wakeup.
wakeup = newWakeup = new Wakeup(newTimeoutAt, wakeup);
@ -114,7 +115,7 @@ public abstract class CyclicTimeout implements Destroyable
LOG.debug("Installed timeout in {} ms, {} wake up in {} ms",
units.toMillis(delay),
newWakeup != null ? "new" : "existing",
TimeUnit.NANOSECONDS.toMillis(wakeup._at - now));
NanoTime.millisElapsed(now, wakeup._at));
}
break;
}
@ -192,7 +193,7 @@ public abstract class CyclicTimeout implements Destroyable
return String.format("%s@%x:%dms,%s",
getClass().getSimpleName(),
hashCode(),
TimeUnit.NANOSECONDS.toMillis(_at - System.nanoTime()),
NanoTime.millisUntil(_at),
_wakeup);
}
}
@ -214,7 +215,7 @@ public abstract class CyclicTimeout implements Destroyable
private void schedule(long now)
{
_task.compareAndSet(null, _scheduler.schedule(this, _at - now, TimeUnit.NANOSECONDS));
_task.compareAndSet(null, _scheduler.schedule(this, NanoTime.elapsed(now, _at), TimeUnit.NANOSECONDS));
}
private void destroy()
@ -227,7 +228,7 @@ public abstract class CyclicTimeout implements Destroyable
@Override
public void run()
{
long now = System.nanoTime();
long now = NanoTime.now();
Wakeup newWakeup = null;
boolean hasExpired = false;
while (true)
@ -258,7 +259,7 @@ public abstract class CyclicTimeout implements Destroyable
wakeup = wakeup._next;
Timeout newTimeout;
if (timeout._at <= now)
if (NanoTime.isBeforeOrSame(timeout._at, now))
{
// We have timed out!
hasExpired = true;
@ -268,7 +269,7 @@ public abstract class CyclicTimeout implements Destroyable
{
// We have not timed out, but we are set to!
// Is the current wakeup good to use? ie before our timeout time?
if (wakeup == null || wakeup._at >= timeout._at)
if (wakeup == null || NanoTime.isBefore(timeout._at, wakeup._at))
// No, we need an earlier wakeup.
wakeup = newWakeup = new Wakeup(timeout._at, wakeup);
newTimeout = new Timeout(timeout._at, wakeup);
@ -299,7 +300,7 @@ public abstract class CyclicTimeout implements Destroyable
return String.format("%s@%x:%dms->%s",
getClass().getSimpleName(),
hashCode(),
_at == MAX_VALUE ? _at : TimeUnit.NANOSECONDS.toMillis(_at - System.nanoTime()),
_at == MAX_VALUE ? _at : NanoTime.millisUntil(_at),
_next);
}
}

View File

@ -17,6 +17,7 @@ import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.component.Destroyable;
import org.eclipse.jetty.util.thread.Scheduler;
import org.slf4j.Logger;
@ -75,7 +76,7 @@ public abstract class CyclicTimeouts<T extends CyclicTimeouts.Expirable> impleme
if (LOG.isDebugEnabled())
LOG.debug("Timeouts check for {}", this);
long now = System.nanoTime();
long now = NanoTime.now();
long earliest = Long.MAX_VALUE;
// Reset the earliest timeout so we can expire again.
// A concurrent call to schedule(long) may lose an
@ -95,12 +96,12 @@ public abstract class CyclicTimeouts<T extends CyclicTimeouts.Expirable> impleme
long expiresAt = expirable.getExpireNanoTime();
if (LOG.isDebugEnabled())
LOG.debug("Entity {} expires in {} ms for {}", expirable, TimeUnit.NANOSECONDS.toMillis(expiresAt - now), this);
LOG.debug("Entity {} expires in {} ms for {}", expirable, NanoTime.millisElapsed(now, expiresAt), this);
if (expiresAt == -1)
continue;
if (expiresAt <= now)
if (NanoTime.isBeforeOrSame(expiresAt, now))
{
boolean remove = onExpired(expirable);
if (LOG.isDebugEnabled())
@ -109,11 +110,12 @@ public abstract class CyclicTimeouts<T extends CyclicTimeouts.Expirable> impleme
iterator.remove();
continue;
}
earliest = Math.min(earliest, expiresAt);
earliest = Math.min(earliest, NanoTime.elapsed(now, expiresAt));
}
if (earliest < Long.MAX_VALUE)
schedule(earliest);
schedule(now + earliest);
}
/**
@ -133,12 +135,12 @@ public abstract class CyclicTimeouts<T extends CyclicTimeouts.Expirable> impleme
// Schedule a timeout for the earliest entity that may expire.
// When the timeout expires, scan the entities for the next
// earliest entity that may expire, and reschedule a new timeout.
long prevEarliest = earliestTimeout.getAndUpdate(t -> Math.min(t, expiresAt));
long prevEarliest = earliestTimeout.getAndUpdate(t -> NanoTime.isBefore(t, expiresAt) ? t : expiresAt);
long expires = expiresAt;
while (expires < prevEarliest)
while (NanoTime.isBefore(expires, prevEarliest))
{
// A new entity expires earlier than previous entities, schedule it.
long delay = Math.max(0, expires - System.nanoTime());
long delay = Math.max(0, NanoTime.until(expires));
if (LOG.isDebugEnabled())
LOG.debug("Scheduling timeout in {} ms for {}", TimeUnit.NANOSECONDS.toMillis(delay), this);
schedule(cyclicTimeout, delay, TimeUnit.NANOSECONDS);
@ -168,9 +170,9 @@ public abstract class CyclicTimeouts<T extends CyclicTimeouts.Expirable> impleme
{
/**
* <p>Returns the expiration time in nanoseconds.</p>
* <p>The value to return must be calculated taking into account {@link System#nanoTime()},
* <p>The value to return must be calculated taking into account the current nanoTime,
* for example:</p>
* {@code expireNanoTime = System.nanoTime() + timeoutNanos}
* {@code expireNanoTime = NanoTime.now() + timeoutNanos}
* <p>Returning {@link Long#MAX_VALUE} indicates that this entity does not expire.</p>
*
* @return the expiration time in nanoseconds, or {@link Long#MAX_VALUE} if this entity does not expire

View File

@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -35,7 +36,7 @@ public abstract class IdleTimeout
private final Scheduler _scheduler;
private final AtomicReference<Scheduler.Task> _timeout = new AtomicReference<>();
private volatile long _idleTimeout;
private volatile long _idleTimestamp = System.nanoTime();
private volatile long _idleNanoTime = NanoTime.now();
/**
* @param scheduler A scheduler used to schedule checks for the idle timeout.
@ -55,7 +56,7 @@ public abstract class IdleTimeout
*/
public long getIdleFor()
{
return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - _idleTimestamp);
return NanoTime.millisSince(_idleNanoTime);
}
/**
@ -100,7 +101,7 @@ public abstract class IdleTimeout
*/
public void notIdle()
{
_idleTimestamp = System.nanoTime();
_idleNanoTime = NanoTime.now();
}
private void idleCheck()
@ -147,8 +148,8 @@ public abstract class IdleTimeout
{
if (isOpen())
{
long idleTimestamp = _idleTimestamp;
long idleElapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - idleTimestamp);
long idleNanoTime = _idleNanoTime;
long idleElapsed = NanoTime.millisSince(idleNanoTime);
long idleTimeout = getIdleTimeout();
long idleLeft = idleTimeout - idleElapsed;

View File

@ -13,6 +13,8 @@
package org.eclipse.jetty.io;
import org.eclipse.jetty.util.NanoTime;
/**
* Extension of the {@link ArrayByteBufferPool} whose bucket sizes increase exponentially instead of linearly.
* Each bucket will be double the size of the previous bucket, this decreases the amounts of buckets required
@ -111,10 +113,10 @@ public class LogarithmicArrayByteBufferPool extends ArrayByteBufferPool
Bucket bucket = buckets[i];
if (bucket.isEmpty())
continue;
long lastUpdate = bucket.getLastUpdate();
if (lastUpdate < oldest)
long lastUpdateNanoTime = bucket.getLastUpdate();
if (oldest == Long.MAX_VALUE || NanoTime.isBefore(lastUpdateNanoTime, oldest))
{
oldest = lastUpdate;
oldest = lastUpdateNanoTime;
index = i;
}
}

View File

@ -24,6 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.component.Dumpable;
@ -203,10 +204,10 @@ public class MappedByteBufferPool extends AbstractByteBufferPool implements Dump
if (bucket.isEmpty())
continue;
long lastUpdate = bucket.getLastUpdate();
if (lastUpdate < oldest)
long lastUpdateNanoTime = bucket.getLastUpdate();
if (oldest == Long.MAX_VALUE || NanoTime.isBefore(lastUpdateNanoTime, oldest))
{
oldest = lastUpdate;
oldest = lastUpdateNanoTime;
index = entry.getKey();
}
}

View File

@ -19,6 +19,7 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.Retainable;
/**
@ -38,7 +39,7 @@ public class RetainableByteBuffer implements Retainable
private final ByteBuffer buffer;
private final AtomicInteger references = new AtomicInteger();
private final Consumer<RetainableByteBuffer> releaser;
private final AtomicLong lastUpdate = new AtomicLong(System.nanoTime());
private final AtomicLong lastUpdate = new AtomicLong(NanoTime.now());
RetainableByteBuffer(ByteBuffer buffer, Consumer<RetainableByteBuffer> releaser)
{
@ -111,7 +112,7 @@ public class RetainableByteBuffer implements Retainable
});
if (ref == 0)
{
lastUpdate.setOpaque(System.nanoTime());
lastUpdate.setOpaque(NanoTime.now());
releaser.accept(this);
return true;
}

View File

@ -21,6 +21,7 @@ import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.Scheduler;
import org.eclipse.jetty.util.thread.TimerScheduler;
import org.junit.jupiter.api.AfterEach;
@ -283,7 +284,7 @@ public class ByteArrayEndPointTest
assertEquals("test", BufferUtil.toString(buffer));
// Wait for a read timeout.
long start = System.nanoTime();
long start = NanoTime.now();
fcb = new FutureCallback();
endp.fillInterested(fcb);
try
@ -295,7 +296,7 @@ public class ByteArrayEndPointTest
{
assertThat(t.getCause(), instanceOf(TimeoutException.class));
}
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start), greaterThan(halfIdleTimeout));
assertThat(NanoTime.millisSince(start), greaterThan(halfIdleTimeout));
assertThat("Endpoint open", endp.isOpen(), is(true));
}
}

View File

@ -15,6 +15,7 @@ package org.eclipse.jetty.io;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -26,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class CyclicTimeoutTest
{
private volatile boolean _expired;
private ScheduledExecutorScheduler _timer = new ScheduledExecutorScheduler();
private final ScheduledExecutorScheduler _timer = new ScheduledExecutorScheduler();
private CyclicTimeout _timeout;
@BeforeEach
@ -132,11 +133,11 @@ public class CyclicTimeoutTest
}
@Test
public void testBusy() throws Exception
public void testBusy()
{
long testUntil = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(2000);
assertTrue(_timeout.schedule(500, TimeUnit.MILLISECONDS));
while (System.nanoTime() < testUntil)
long start = NanoTime.now();
while (NanoTime.secondsSince(start) < 2)
_timeout.schedule(500, TimeUnit.MILLISECONDS);
_timeout.cancel();
assertFalse(_expired);

View File

@ -23,6 +23,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;
import org.eclipse.jetty.util.thread.Scheduler;
@ -231,25 +232,25 @@ public class CyclicTimeoutsTest
return new ConstantExpirable(delay, unit);
}
private final long expireNanos;
private final long expireNanoTime;
private final String asString;
private ConstantExpirable()
{
this.expireNanos = Long.MAX_VALUE;
this.expireNanoTime = Long.MAX_VALUE;
this.asString = "noexp";
}
public ConstantExpirable(long delay, TimeUnit unit)
{
this.expireNanos = System.nanoTime() + unit.toNanos(delay);
this.expireNanoTime = NanoTime.now() + unit.toNanos(delay);
this.asString = String.valueOf(unit.toMillis(delay));
}
@Override
public long getExpireNanoTime()
{
return expireNanos;
return expireNanoTime;
}
@Override

View File

@ -13,9 +13,9 @@
package org.eclipse.jetty.io;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.TimerScheduler;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -126,8 +126,8 @@ public class IdleTimeoutTest
assertNull(_expired);
_timeout.setIdleTimeout(100);
long start = System.nanoTime();
while (_expired == null && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start) < 5)
long start = NanoTime.now();
while (_expired == null && NanoTime.secondsSince(start) < 5)
{
Thread.sleep(200);
}

View File

@ -43,6 +43,7 @@ import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.Scheduler;
@ -99,8 +100,8 @@ public class SocketChannelEndPointTest
private CountDownLatch _lastEndPointLatch;
// Must be volatile or the test may fail spuriously
private AtomicInteger _blockAt = new AtomicInteger(0);
private AtomicInteger _writeCount = new AtomicInteger(1);
private final AtomicInteger _blockAt = new AtomicInteger(0);
private final AtomicInteger _writeCount = new AtomicInteger(1);
public void init(Scenario scenario) throws Exception
{
@ -152,10 +153,9 @@ public class SocketChannelEndPointTest
// wait for read timeout
client.setSoTimeout(500);
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
assertThrows(SocketTimeoutException.class, () -> client.getInputStream().read());
long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start;
assertThat("timeout duration", duration, greaterThanOrEqualTo(400L));
assertThat(NanoTime.millisSince(start), greaterThanOrEqualTo(400L));
// write then shutdown
client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8));
@ -207,9 +207,9 @@ public class SocketChannelEndPointTest
}
// wait for read timeout
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
assertThrows(SocketTimeoutException.class, () -> client.getInputStream().read());
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start >= 400);
assertThat(NanoTime.millisSince(start), greaterThanOrEqualTo(400L));
// write then shutdown
client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8));
@ -255,10 +255,9 @@ public class SocketChannelEndPointTest
_lastEndPoint.setIdleTimeout(10 * specifiedTimeout);
Thread.sleep((11 * specifiedTimeout) / 10);
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
assertThrows(SocketTimeoutException.class, () -> clientInputStream.read());
int elapsed = (int)(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start);
assertThat("Expected timeout", elapsed, greaterThanOrEqualTo(3 * specifiedTimeout / 4));
long start = NanoTime.now();
assertThrows(SocketTimeoutException.class, clientInputStream::read);
assertThat(NanoTime.millisSince(start), greaterThanOrEqualTo(3L * specifiedTimeout / 4));
// write remaining characters
clientOutputStream.write("90ABCDEF".getBytes(StandardCharsets.UTF_8));
@ -294,7 +293,7 @@ public class SocketChannelEndPointTest
BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream());
final CountDownLatch latch = new CountDownLatch(writes);
final InputStream in = new BufferedInputStream(client.getInputStream());
final long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
final long start = NanoTime.now();
out.write(bytes);
out.write(count);
out.flush();
@ -326,7 +325,7 @@ public class SocketChannelEndPointTest
count1 = count1 * 10 + (b - '0');
b = in.read();
}
last = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
last = NanoTime.now();
//if (latch.getCount()%1000==0)
// System.out.println(writes-latch.getCount());
@ -336,12 +335,11 @@ public class SocketChannelEndPointTest
}
catch (Throwable e)
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long now = NanoTime.now();
System.err.println("count=" + count1);
System.err.println("latch=" + latch.getCount());
System.err.println("time=" + (now - start));
System.err.println("last=" + (now - last));
System.err.println("time=" + NanoTime.millisElapsed(start, now));
System.err.println("last=" + NanoTime.millisElapsed(last, now));
System.err.println("endp=" + _lastEndPoint);
System.err.println("conn=" + _lastEndPoint.getConnection());
@ -677,7 +675,6 @@ public class SocketChannelEndPointTest
// volatile int _blockAt = 0;
ByteBuffer _in = BufferUtil.allocate(32 * 1024);
ByteBuffer _out = BufferUtil.allocate(32 * 1024);
long _last = -1;
final CountDownLatch _latch;
public TestConnection(EndPoint endp, Executor executor, AtomicInteger blockAt, AtomicInteger writeCount)
@ -742,7 +739,6 @@ public class SocketChannelEndPointTest
EndPoint endPoint = getEndPoint();
try
{
_last = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
boolean progress = true;
while (progress)
{

View File

@ -20,12 +20,12 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContainerInitializer;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
@ -130,9 +130,9 @@ public class ContainerInitializer
context.getServletContext().setExtendedListenerTypes(true);
if (LOG.isDebugEnabled())
{
long start = System.nanoTime();
long start = NanoTime.now();
_target.onStartup(classes, context.getServletContext());
LOG.debug("ContainerInitializer {} called in {}ms", _target.getClass().getName(), TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
LOG.debug("ContainerInitializer {} called in {}ms", _target.getClass().getName(), NanoTime.millisSince(start));
}
else
_target.onStartup(classes, context.getServletContext());

View File

@ -21,6 +21,7 @@ import org.eclipse.jetty.jndi.NamingContext;
import org.eclipse.jetty.plus.annotation.InjectionCollection;
import org.eclipse.jetty.plus.annotation.LifeCycleCallbackCollection;
import org.eclipse.jetty.plus.jndi.Transaction;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.webapp.AbstractConfiguration;
import org.eclipse.jetty.webapp.FragmentConfiguration;
import org.eclipse.jetty.webapp.JettyWebXmlConfiguration;
@ -104,7 +105,7 @@ public class PlusConfiguration extends AbstractConfiguration
Thread.currentThread().setContextClassLoader(wac.getClassLoader());
try
{
_key = (int)(this.hashCode() ^ System.nanoTime());
_key = (int)(this.hashCode() ^ NanoTime.now());
Context context = new InitialContext();
Context compCtx = (Context)context.lookup("java:comp");
compCtx.addToEnvironment(NamingContext.LOCK_PROPERTY, _key);

View File

@ -31,6 +31,7 @@ import org.eclipse.jetty.quic.common.QuicStreamEndPoint;
import org.eclipse.jetty.quic.quiche.QuicheConnection;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.Scheduler;
/**
@ -120,6 +121,6 @@ public class ServerQuicSession extends QuicSession implements CyclicTimeouts.Exp
{
long idleTimeout = getIdleTimeout();
if (idleTimeout > 0)
expireNanoTime = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(idleTimeout);
expireNanoTime = NanoTime.now() + TimeUnit.MILLISECONDS.toNanos(idleTimeout);
}
}

View File

@ -34,6 +34,7 @@ import java.util.jar.JarOutputStream;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.security.Credential;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.Test;
@ -52,10 +53,10 @@ import static org.junit.jupiter.api.condition.OS.MAC;
@ExtendWith(WorkDirExtension.class)
public class PropertyUserStoreTest
{
private final class UserCount implements PropertyUserStore.UserListener
private static final class UserCount implements PropertyUserStore.UserListener
{
private final AtomicInteger userCount = new AtomicInteger();
private final List<String> users = new ArrayList<String>();
private final List<String> users = new ArrayList<>();
private UserCount()
{
@ -80,9 +81,8 @@ public class PropertyUserStoreTest
public void awaitCount(int expectedCount) throws InterruptedException
{
long timeout = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) + TimeUnit.SECONDS.toMillis(10);
while (userCount.get() != expectedCount && (TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) < timeout))
long start = NanoTime.now();
while (userCount.get() != expectedCount && NanoTime.secondsSince(start) < 10)
{
TimeUnit.MILLISECONDS.sleep(100);
}
@ -193,7 +193,7 @@ public class PropertyUserStoreTest
}
@Test
public void testPropertyUserStoreFails() throws Exception
public void testPropertyUserStoreFails()
{
assertThrows(IllegalStateException.class, () ->
{

View File

@ -19,6 +19,7 @@ import java.util.concurrent.locks.Condition;
import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.StaticException;
import org.eclipse.jetty.util.component.Destroyable;
import org.eclipse.jetty.util.thread.AutoLock;
@ -41,7 +42,7 @@ class AsyncContentProducer implements ContentProducer
private HttpInput.Content _rawContent;
private HttpInput.Content _transformedContent;
private boolean _error;
private long _firstByteTimeStamp = Long.MIN_VALUE;
private long _firstByteNanoTime = Long.MIN_VALUE;
private long _rawContentArrived;
AsyncContentProducer(HttpChannel httpChannel)
@ -88,7 +89,7 @@ class AsyncContentProducer implements ContentProducer
_rawContent = null;
_transformedContent = null;
_error = false;
_firstByteTimeStamp = Long.MIN_VALUE;
_firstByteNanoTime = Long.MIN_VALUE;
_rawContentArrived = 0L;
}
@ -142,10 +143,10 @@ class AsyncContentProducer implements ContentProducer
assertLocked();
long minRequestDataRate = _httpChannel.getHttpConfiguration().getMinRequestDataRate();
if (LOG.isDebugEnabled())
LOG.debug("checkMinDataRate [m={},t={}] {}", minRequestDataRate, _firstByteTimeStamp, this);
if (minRequestDataRate > 0 && _firstByteTimeStamp != Long.MIN_VALUE)
LOG.debug("checkMinDataRate [m={},t={}] {}", minRequestDataRate, _firstByteNanoTime, this);
if (minRequestDataRate > 0 && _firstByteNanoTime != Long.MIN_VALUE)
{
long period = System.nanoTime() - _firstByteTimeStamp;
long period = NanoTime.since(_firstByteNanoTime);
if (period > 0)
{
long minimumData = minRequestDataRate * TimeUnit.NANOSECONDS.toMillis(period) / TimeUnit.SECONDS.toMillis(1);
@ -489,10 +490,10 @@ class AsyncContentProducer implements ContentProducer
if (content != null)
{
_rawContentArrived += content.remaining();
if (_firstByteTimeStamp == Long.MIN_VALUE)
_firstByteTimeStamp = System.nanoTime();
if (_firstByteNanoTime == Long.MIN_VALUE)
_firstByteNanoTime = NanoTime.now();
if (LOG.isDebugEnabled())
LOG.debug("produceRawContent updated rawContentArrived to {} and firstByteTimeStamp to {} {}", _rawContentArrived, _firstByteTimeStamp, this);
LOG.debug("produceRawContent updated rawContentArrived to {} and firstByteTimeStamp to {} {}", _rawContentArrived, _firstByteNanoTime, this);
}
if (LOG.isDebugEnabled())
LOG.debug("produceRawContent produced {} {}", content, this);

View File

@ -38,6 +38,7 @@ import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.IteratingCallback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.SharedBlockingCallback;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.eclipse.jetty.util.thread.AutoLock;
@ -184,7 +185,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
private Interceptor _interceptor;
private long _written;
private long _flushed;
private long _firstByteTimeStamp = -1;
private long _firstByteNanoTime = -1;
private ByteBuffer _aggregate;
private int _bufferSize;
private int _commitSize;
@ -257,13 +258,13 @@ public class HttpOutput extends ServletOutputStream implements Runnable
private void channelWrite(ByteBuffer content, boolean last, Callback callback)
{
if (_firstByteTimeStamp == -1)
if (_firstByteNanoTime == -1)
{
long minDataRate = getHttpChannel().getHttpConfiguration().getMinResponseDataRate();
if (minDataRate > 0)
_firstByteTimeStamp = System.nanoTime();
_firstByteNanoTime = NanoTime.now();
else
_firstByteTimeStamp = Long.MAX_VALUE;
_firstByteNanoTime = Long.MAX_VALUE;
}
_interceptor.write(content, last, callback);
@ -1373,11 +1374,11 @@ public class HttpOutput extends ServletOutputStream implements Runnable
*/
public void onFlushed(long bytes) throws IOException
{
if (_firstByteTimeStamp == -1 || _firstByteTimeStamp == Long.MAX_VALUE)
if (_firstByteNanoTime == -1 || _firstByteNanoTime == Long.MAX_VALUE)
return;
long minDataRate = getHttpChannel().getHttpConfiguration().getMinResponseDataRate();
_flushed += bytes;
long elapsed = System.nanoTime() - _firstByteTimeStamp;
long elapsed = NanoTime.since(_firstByteNanoTime);
long minFlushed = minDataRate * TimeUnit.NANOSECONDS.toMillis(elapsed) / TimeUnit.SECONDS.toMillis(1);
if (LOG.isDebugEnabled())
LOG.debug("Flushed bytes min/actual {}/{}", minFlushed, _flushed);
@ -1406,7 +1407,7 @@ public class HttpOutput extends ServletOutputStream implements Runnable
_written = 0;
_writeListener = null;
_onError = null;
_firstByteTimeStamp = -1;
_firstByteNanoTime = -1;
_flushed = 0;
_closedCallback = null;
}

View File

@ -46,6 +46,7 @@ import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.Jetty;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.Uptime;
@ -483,7 +484,7 @@ public class Server extends HandlerWrapper implements Attributes
if (getStopTimeout() > 0)
{
long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(getStopTimeout());
long end = NanoTime.now() + TimeUnit.MILLISECONDS.toNanos(getStopTimeout());
try
{
Graceful.shutdown(this).get(getStopTimeout(), TimeUnit.MILLISECONDS);
@ -494,7 +495,7 @@ public class Server extends HandlerWrapper implements Attributes
}
QueuedThreadPool qtp = getBean(QueuedThreadPool.class);
if (qtp != null)
qtp.setStopTimeout(Math.max(1000L, TimeUnit.NANOSECONDS.toMillis(end - System.nanoTime())));
qtp.setStopTimeout(Math.max(1000L, NanoTime.millisUntil(end)));
}
// Now stop the connectors (this will close existing connections)

View File

@ -48,6 +48,7 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.Scheduler;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
@ -226,10 +227,10 @@ public class AsyncCompletionTest extends HttpServerTestFixture
}
// OWP has exited, but we have a delay, so let's wait for thread to return to the pool to ensure we are async.
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(WAIT);
long start = NanoTime.now();
while (delay != null && _threadPool.getBusyThreads() > base)
{
if (System.nanoTime() > end)
if (NanoTime.secondsSince(start) > WAIT)
throw new TimeoutException();
Thread.sleep(POLL);
}
@ -246,10 +247,10 @@ public class AsyncCompletionTest extends HttpServerTestFixture
}
// Wait for full completion
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(WAIT);
long start = NanoTime.now();
while (!__transportComplete.get())
{
if (System.nanoTime() > end)
if (NanoTime.secondsSince(start) > WAIT)
throw new TimeoutException();
// proceed with any delayCBs needed for completion
@ -487,10 +488,10 @@ public class AsyncCompletionTest extends HttpServerTestFixture
handler.wait4handle();
// Wait for full completion
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(WAIT);
long start = NanoTime.now();
while (!__transportComplete.get())
{
if (System.nanoTime() > end)
if (NanoTime.secondsSince(start) > WAIT)
throw new TimeoutException();
// proceed with any delayCBs needed for completion
@ -648,19 +649,19 @@ public class AsyncCompletionTest extends HttpServerTestFixture
handler.wait4handle();
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(WAIT);
long start = NanoTime.now();
while (_threadPool.getBusyThreads() != base)
{
if (System.nanoTime() > end)
if (NanoTime.secondsSince(start) > WAIT)
throw new TimeoutException();
Thread.sleep(POLL);
}
// Wait for full completion
end = System.nanoTime() + TimeUnit.SECONDS.toNanos(WAIT);
start = NanoTime.now();
while (!__transportComplete.get())
{
if (System.nanoTime() > end)
if (NanoTime.secondsSince(start) > WAIT)
throw new TimeoutException();
// proceed with any delayCBs needed for completion

View File

@ -21,7 +21,6 @@ import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
@ -120,11 +119,9 @@ public class AsyncStressTest
int period = _random.nextInt(290) + 10;
String uri = StringUtil.replace(__paths[p][0], "<PERIOD>", Integer.toString(period));
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
String request =
"GET " + uri + " HTTP/1.1\r\n" +
"Host: localhost\r\n" +
"start: " + start + "\r\n" +
"result: " + __paths[p][1] + "\r\n" +
((l + 1 < loops) ? "" : "Connection: close\r\n") +
"\r\n";

View File

@ -36,6 +36,7 @@ import org.eclipse.jetty.io.ssl.SslConnection;
import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
@ -61,10 +62,10 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
{
protected static final Logger LOG = LoggerFactory.getLogger(ConnectorTimeoutTest.class);
protected static final int MAX_IDLE_TIME = 2000;
private int sleepTime = MAX_IDLE_TIME + MAX_IDLE_TIME / 5;
private int minimumTestRuntime = MAX_IDLE_TIME - MAX_IDLE_TIME / 5;
private int maximumTestRuntime = MAX_IDLE_TIME * 10;
protected static final long MAX_IDLE_TIME = 2000;
private final long sleepTime = MAX_IDLE_TIME + MAX_IDLE_TIME / 5;
private final long minimumTestRuntime = MAX_IDLE_TIME - MAX_IDLE_TIME / 5;
private final long maximumTestRuntime = MAX_IDLE_TIME * 10;
static
{
@ -96,7 +97,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
assertTimeoutPreemptively(ofSeconds(10), () ->
{
@ -113,8 +114,9 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
assertEquals(-1, is.read());
});
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start > minimumTestRuntime);
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime);
long elapsedMs = NanoTime.millisSince(start);
assertTrue(elapsedMs > minimumTestRuntime);
assertTrue(elapsedMs < maximumTestRuntime);
}
@Test
@ -129,7 +131,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
assertTimeoutPreemptively(ofSeconds(10), () ->
{
@ -150,8 +152,9 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
assertEquals(-1, is.read());
});
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start > minimumTestRuntime);
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime);
long elapsedMs = NanoTime.millisSince(start);
assertTrue(elapsedMs > minimumTestRuntime);
assertTrue(elapsedMs < maximumTestRuntime);
}
@Test
@ -287,7 +290,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
InputStream is = client.getInputStream();
assertFalse(client.isClosed());
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
OutputStream os = client.getOutputStream();
os.write(("GET / HTTP/1.1\r\n" +
@ -325,7 +328,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
{
e.printStackTrace();
}
long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start;
long duration = NanoTime.millisSince(start);
assertThat(duration, greaterThan(500L));
assertTimeoutPreemptively(ofSeconds(10), () ->
@ -350,7 +353,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
OutputStream os = client.getOutputStream();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
os.write(("GET / HTTP/1.1\r\n" +
"host: localhost:" + _serverURI.getPort() + "\r\n" +
"Transfer-Encoding: chunked\r\n" +
@ -383,7 +386,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
os.flush();
}
long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start;
long duration = NanoTime.millisSince(start);
assertThat(duration, greaterThan(500L));
// read the response
@ -428,7 +431,6 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
if (i % 1028 == 0)
{
Thread.sleep(20);
// System.err.println("read "+TimeUnit.NANOSECONDS.toMillis(System.nanoTime()));
}
line = is.readLine();
assertThat(line, notNullValue());
@ -466,7 +468,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
line = is.readLine();
}
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class, AbstractConnection.class))
{
for (int i = 0; i < (128 * 1024); i++)
@ -474,16 +476,13 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
if (i % 1028 == 0)
{
Thread.sleep(20);
// System.err.println("read "+TimeUnit.NANOSECONDS.toMillis(System.nanoTime()));
}
line = is.readLine();
if (line == null)
break;
}
}
long end = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long duration = end - start;
assertThat(duration, lessThan(20L * 128L));
assertThat(NanoTime.millisSince(start), lessThan(20L * 128L));
}
@Test
@ -496,7 +495,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
assertFalse(client.isClosed());
OutputStream os = client.getOutputStream();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
os.write("GET ".getBytes("utf-8"));
os.flush();
@ -514,14 +513,14 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
LOG.warn(e.getMessage());
}
});
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime);
assertTrue(NanoTime.millisSince(start) < maximumTestRuntime);
}
@Test
public void testMaxIdleNothingSent() throws Exception
{
configureServer(new EchoHandler());
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
client.setSoTimeout(10000);
InputStream is = client.getInputStream();
@ -545,7 +544,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
LOG.warn("Unable to read stream", e);
}
});
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start < maximumTestRuntime);
assertTrue(NanoTime.millisSince(start) < maximumTestRuntime);
}
@Test
@ -558,7 +557,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
assertFalse(client.isClosed());
OutputStream os = client.getOutputStream();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
os.write((
"GET / HTTP/1.1\r\n" +
"host: localhost:" + _serverURI.getPort() + "\r\n" +
@ -582,7 +581,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
e.printStackTrace();
}
});
int duration = (int)(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start);
long duration = NanoTime.millisSince(start);
assertThat(duration, greaterThanOrEqualTo(MAX_IDLE_TIME));
assertThat(duration, lessThan(maximumTestRuntime));
}
@ -597,7 +596,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
assertFalse(client.isClosed());
OutputStream os = client.getOutputStream();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
os.write((
"GET / HTTP/1.1\r\n" +
"host: localhost:" + _serverURI.getPort() + "\r\n" +
@ -622,7 +621,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
e.printStackTrace();
}
});
int duration = (int)(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start);
long duration = NanoTime.millisSince(start);
assertThat(duration + 100, greaterThanOrEqualTo(MAX_IDLE_TIME));
assertThat(duration - 100, lessThan(maximumTestRuntime));
}

View File

@ -19,7 +19,6 @@ import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -30,6 +29,7 @@ import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.ManagedSelector;
import org.eclipse.jetty.io.SocketChannelEndPoint;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.Scheduler;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
@ -74,7 +74,7 @@ public class ExtendedServerTest extends HttpServerTestBase
@Override
public Runnable onSelected()
{
_lastSelected = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
_lastSelected = NanoTime.now();
return super.onSelected();
}
@ -115,11 +115,11 @@ public class ExtendedServerTest extends HttpServerTestBase
{
OutputStream os = client.getOutputStream();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
os.write("GET / HTTP/1.0\r\n".getBytes(StandardCharsets.ISO_8859_1));
os.flush();
Thread.sleep(200);
long end = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long end = NanoTime.now();
os.write("\r\n".getBytes(StandardCharsets.ISO_8859_1));
// Read the response.
@ -132,8 +132,8 @@ public class ExtendedServerTest extends HttpServerTestBase
s = s.substring(0, s.indexOf('\n'));
long dispatched = Long.parseLong(s);
assertThat(dispatched, Matchers.greaterThanOrEqualTo(start));
assertThat(dispatched, Matchers.lessThan(end));
assertThat(NanoTime.elapsed(start, dispatched), Matchers.greaterThanOrEqualTo(0L));
assertThat(NanoTime.elapsed(dispatched, end), Matchers.greaterThanOrEqualTo(0L));
}
}

View File

@ -35,6 +35,7 @@ import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.StatisticsHandler;
import org.eclipse.jetty.util.FuturePromise;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.component.Graceful;
import org.eclipse.jetty.util.component.LifeCycle;
import org.hamcrest.Matchers;
@ -46,6 +47,7 @@ import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class GracefulStopTest
@ -148,6 +150,7 @@ public class GracefulStopTest
assertTrue(handler.latch.await(5, TimeUnit.SECONDS));
HttpTester.Response response = HttpTester.parseResponse(client.getInputStream());
assertNotNull(response);
assertThat(response.getStatus(), is(200));
assertThat(response.getContent(), is("read [10/10]"));
assertThat(response.get(HttpHeader.CONNECTION), nullValue());
@ -163,6 +166,7 @@ public class GracefulStopTest
assertTrue(handler.latch.await(5, TimeUnit.SECONDS));
HttpTester.Response response = HttpTester.parseResponse(client.getInputStream());
assertNotNull(response);
assertThat(response.getStatus(), is(200));
assertThat(response.getContent(), is("read [10/10]"));
assertThat(response.get(HttpHeader.CONNECTION), nullValue());
@ -171,21 +175,21 @@ public class GracefulStopTest
Future<Integer> backgroundUnavailable(Socket client, byte[] post, ContextHandler context, TestHandler handler) throws Exception
{
FuturePromise<Integer> future = new FuturePromise<>();
long start = System.nanoTime();
long start = NanoTime.now();
new Thread(() ->
{
try
{
while (context.isAvailable())
{
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start), lessThan(5000L));
assertThat(NanoTime.millisSince(start), lessThan(5000L));
Thread.sleep(100);
}
client.getOutputStream().write(concat(post, BODY_67890));
client.getOutputStream().flush();
HttpTester.Response response = HttpTester.parseResponse(client.getInputStream());
assertNotNull(response);
future.succeeded(response.getStatus());
}
catch (Exception e)
@ -199,19 +203,16 @@ public class GracefulStopTest
void assertQuickStop() throws Exception
{
long start = System.nanoTime();
long start = NanoTime.now();
server.stop();
long stop = System.nanoTime();
long duration = TimeUnit.NANOSECONDS.toMillis(stop - start);
assertThat(duration, lessThan(2000L));
assertThat(NanoTime.millisSince(start), lessThan(2000L));
}
void assertGracefulStop(LifeCycle lifecycle) throws Exception
{
long start = System.nanoTime();
long start = NanoTime.now();
lifecycle.stop();
long stop = System.nanoTime();
long duration = TimeUnit.NANOSECONDS.toMillis(stop - start);
long duration = NanoTime.millisSince(start);
assertThat(duration, greaterThan(50L));
assertThat(duration, lessThan(5000L));
}
@ -219,6 +220,7 @@ public class GracefulStopTest
void assertResponse(Socket client, boolean close) throws Exception
{
HttpTester.Response response = HttpTester.parseResponse(client.getInputStream());
assertNotNull(response);
assertThat(response.getStatus(), is(200));
if (close)
assertThat(response.get(HttpHeader.CONNECTION), is("close"));
@ -239,11 +241,9 @@ public class GracefulStopTest
void assertQuickClose(Socket client) throws Exception
{
long start = System.nanoTime();
long start = NanoTime.now();
assertThat(client.getInputStream().read(), is(-1));
long stop = System.nanoTime();
long duration = TimeUnit.NANOSECONDS.toMillis(stop - start);
assertThat(duration, lessThan(2000L));
assertThat(NanoTime.millisSince(start), lessThan(2000L));
}
void assertHandled(TestHandler handler, boolean error)
@ -257,14 +257,13 @@ public class GracefulStopTest
void backgroundComplete(Socket client, TestHandler handler) throws Exception
{
long start = System.nanoTime();
long start = NanoTime.now();
new Thread(() ->
{
try
{
handler.latch.await();
long now = System.nanoTime();
Thread.sleep(100 - TimeUnit.NANOSECONDS.toMillis(now - start));
Thread.sleep(100 - NanoTime.millisSince(start));
client.getOutputStream().write(BODY_67890);
}
catch (Exception e)

View File

@ -30,6 +30,7 @@ import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.NanoTime;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@ -265,15 +266,14 @@ public class HttpChannelEventTest
@Override
public void onRequestBegin(Request request)
{
request.setAttribute(attribute, System.nanoTime());
request.setAttribute(attribute, NanoTime.now());
}
@Override
public void onComplete(Request request)
{
long endTime = System.nanoTime();
long beginTime = (Long)request.getAttribute(attribute);
elapsed.set(endTime - beginTime);
elapsed.set(NanoTime.since(beginTime));
latch.countDown();
}
});

View File

@ -51,6 +51,7 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -998,9 +999,9 @@ public class HttpConnectionTest
"5;\r\n" +
"12345\r\n";
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
String response = connector.getResponse(requests, 2000, TimeUnit.MILLISECONDS);
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, lessThanOrEqualTo(2000L));
assertThat(NanoTime.millisSince(start), lessThanOrEqualTo(2000L));
offset = checkContains(response, offset, "HTTP/1.1 200");
offset = checkContains(response, offset, "pathInfo=/R1");

View File

@ -30,6 +30,7 @@ import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@ -958,10 +959,10 @@ public class HttpManyWaysToAsyncCommitTest extends AbstractHttpTest
{
server.getThreadPool().execute(() ->
{
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
long start = NanoTime.now();
try
{
while (System.nanoTime() < end)
while (NanoTime.secondsSince(start) < 10)
{
switch (request.getHttpChannelState().getState())
{

View File

@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.NanoTime;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -499,10 +500,9 @@ public class LocalAsyncContextTest
static <T> void spinAssertEquals(T expected, Supplier<T> actualSupplier, long waitFor, TimeUnit units)
{
long now = System.nanoTime();
long end = now + units.toNanos(waitFor);
T actual = null;
while (now < end)
long start = NanoTime.now();
while (NanoTime.since(start) < units.toNanos(waitFor))
{
actual = actualSupplier.get();
if (actual == null && expected == null ||
@ -516,7 +516,6 @@ public class LocalAsyncContextTest
{
// Ignored
}
now = System.nanoTime();
}
assertEquals(expected, actual);

View File

@ -27,6 +27,7 @@ import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.server.LocalConnector.LocalEndPoint;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.NanoTime;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -435,7 +436,7 @@ public class NotAcceptingTest
public static <T> void waitFor(Supplier<T> value, Matcher<T> matcher, long wait, TimeUnit units)
{
long start = System.nanoTime();
long start = NanoTime.now();
while (true)
{
@ -446,7 +447,7 @@ public class NotAcceptingTest
}
catch (Throwable e)
{
if ((System.nanoTime() - start) > units.toNanos(wait))
if (NanoTime.since(start) > units.toNanos(wait))
throw e;
}

View File

@ -80,6 +80,7 @@ import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -1746,14 +1747,13 @@ public class RequestTest
"\r\n" +
buf;
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
String rawResponse = _connector.getResponse(request);
HttpTester.Response response = HttpTester.parseResponse(rawResponse);
assertThat("Response.status", response.getStatus(), is(400));
assertThat("Response body content", response.getContent(), containsString(BadMessageException.class.getName()));
assertThat("Response body content", response.getContent(), containsString(IllegalStateException.class.getName()));
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
assertTrue((now - start) < 5000);
assertTrue(NanoTime.millisSince(start) < 5000);
}
}
@ -1785,14 +1785,13 @@ public class RequestTest
"\r\n" +
buf;
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
String rawResponse = _connector.getResponse(request);
HttpTester.Response response = HttpTester.parseResponse(rawResponse);
assertThat("Response.status", response.getStatus(), is(400));
assertThat("Response body content", response.getContent(), containsString(BadMessageException.class.getName()));
assertThat("Response body content", response.getContent(), containsString(IllegalStateException.class.getName()));
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
assertTrue((now - start) < 5000);
assertTrue(NanoTime.millisSince(start) < 5000);
}
}

View File

@ -28,6 +28,7 @@ import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.io.ManagedSelector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@ -82,7 +83,7 @@ public class ServerConnectorAcceptTest
{
assertTrue(awaitBarrier(barrier));
long start = System.nanoTime();
long start = NanoTime.now();
for (int i = 0; i < iterations; ++i)
{
try (Socket socket = new Socket("localhost", connector.getLocalPort()))
@ -105,12 +106,11 @@ public class ServerConnectorAcceptTest
latch.countDown();
}
}
long elapsed = System.nanoTime() - start;
System.err.printf("%d acceptors, %d threads, %d requests each, time = %d ms%n",
acceptors,
threads,
iterations,
TimeUnit.NANOSECONDS.toMillis(elapsed));
NanoTime.millisSince(start));
}
finally
{

View File

@ -30,6 +30,7 @@ import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -135,13 +136,12 @@ public class ServerConnectorTimeoutTest extends ConnectorTimeoutTest
{
try (Socket socket = new Socket((String)null, _connector.getLocalPort()))
{
socket.setSoTimeout(10 * MAX_IDLE_TIME);
socket.setSoTimeout((int)(10 * MAX_IDLE_TIME));
socket.getOutputStream().write(request.getBytes(StandardCharsets.UTF_8));
InputStream inputStream = socket.getInputStream();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
String response = IO.toString(inputStream);
long timeElapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start;
assertThat(timeElapsed, greaterThanOrEqualTo(MAX_IDLE_TIME - 100L));
assertThat(NanoTime.millisSince(start), greaterThanOrEqualTo(MAX_IDLE_TIME - 100L));
return response;
}
}

View File

@ -36,6 +36,7 @@ import org.eclipse.jetty.server.handler.StatisticsHandler;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.FutureCallback;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.component.LifeCycle;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
@ -156,12 +157,12 @@ public class StopTest
@Override
public void close()
{
long start = System.nanoTime();
long start = NanoTime.now();
new Thread(() ->
{
try
{
Thread.sleep(closeWait - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
Thread.sleep(closeWait - NanoTime.millisSince(start));
}
catch (Throwable e)
{
@ -206,7 +207,7 @@ public class StopTest
break;
}
long start = System.nanoTime();
long start = NanoTime.now();
try
{
server.stop();
@ -216,10 +217,9 @@ public class StopTest
{
assertTrue(stopTimeout > 0 && stopTimeout < closeWait);
}
long stop = System.nanoTime();
// Check stop time was correct
assertThat(TimeUnit.NANOSECONDS.toMillis(stop - start), stopTimeMatcher);
assertThat(NanoTime.millisSince(start), stopTimeMatcher);
// Connection closed
while (true)
@ -227,7 +227,7 @@ public class StopTest
int r = client.getInputStream().read();
if (r == -1)
break;
assertThat(TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start), lessThan(10L));
assertThat(NanoTime.millisSince(start), lessThan(10L));
}
// onClose Thread interrupted or completed
@ -344,10 +344,10 @@ public class StopTest
}
}).start();
long start = System.nanoTime();
long start = NanoTime.now();
while (!connector.isShutdown())
{
assertThat(TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start), lessThan(10L));
assertThat(NanoTime.secondsSince(start), lessThan(10L));
Thread.sleep(10);
}

View File

@ -18,7 +18,6 @@ import java.net.Socket;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -26,6 +25,7 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
@ -345,11 +345,11 @@ public class StressTest
{
if (persistent)
{
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
Socket socket = new Socket("localhost", _connector.getLocalPort());
socket.setSoTimeout(30000);
long connected = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long connected = NanoTime.now();
for (int i = 0; i < __tests.length; i++)
{
@ -367,21 +367,21 @@ public class StressTest
Thread.yield();
}
long written = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long written = NanoTime.now();
String response = IO.toString(socket.getInputStream());
socket.close();
long end = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long end = NanoTime.now();
int bodies = count(response, "HTTP/1.1 200 OK");
if (__tests.length != bodies)
System.err.println("responses=\n" + response + "\n---");
assertEquals(__tests.length, bodies, name);
long bind = connected - start;
long flush = (written - connected) / __tests.length;
long read = (end - written) / __tests.length;
long bind = NanoTime.millisElapsed(start, connected);
long flush = NanoTime.millisElapsed(connected, written) / __tests.length;
long read = NanoTime.millisElapsed(written, end) / __tests.length;
int offset = 0;
for (int i = 0; i < __tests.length; i++)
@ -406,7 +406,7 @@ public class StressTest
{
String uri = __tests[i] + "/" + name + "/" + i;
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
String close = "Connection: close\r\n";
String request =
"GET " + uri + " HTTP/1.1\r\n" +
@ -417,23 +417,23 @@ public class StressTest
Socket socket = new Socket("localhost", _connector.getLocalPort());
socket.setSoTimeout(10000);
_latencies[0].add((TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start));
_latencies[0].add(NanoTime.millisSince(start));
socket.getOutputStream().write(request.getBytes());
socket.getOutputStream().flush();
_latencies[1].add((TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start));
_latencies[1].add(NanoTime.millisSince(start));
String response = IO.toString(socket.getInputStream());
socket.close();
long end = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long end = NanoTime.now();
String endOfResponse = "\r\n\r\n";
assertThat(response, containsString(endOfResponse));
response = response.substring(response.indexOf(endOfResponse) + endOfResponse.length());
assertThat(uri, response, startsWith("DATA " + __tests[i]));
long latency = end - start;
long latency = NanoTime.millisElapsed(start, end);
_latencies[5].add(latency);
}
@ -458,24 +458,19 @@ public class StressTest
@Override
public void handle(String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long now = NanoTime.now();
long start = Long.parseLong(baseRequest.getHeader("start"));
long received = baseRequest.getTimeStamp();
_handled.incrementAndGet();
long delay = received - start;
if (delay < 0)
delay = 0;
long delay = NanoTime.millisElapsed(start, now);
_latencies[2].add(delay);
_latencies[3].add((now - start));
_latencies[3].add(delay);
response.setStatus(200);
response.getOutputStream().print("DATA " + request.getPathInfo() + "\n\n");
baseRequest.setHandled(true);
_latencies[4].add((TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start));
return;
_latencies[4].add(NanoTime.millisSince(start));
}
}
}

View File

@ -16,7 +16,6 @@ package org.eclipse.jetty.server.handler;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.ServletException;
@ -30,6 +29,7 @@ import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.NanoTime;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -212,8 +212,9 @@ public class ThreadLimitHandlerTest
client[i].getOutputStream().flush();
}
long wait = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (count.get() < 4 && System.nanoTime() < wait)
long wait = 10;
long start = NanoTime.now();
while (count.get() < 4 && NanoTime.secondsSince(start) < wait)
{
Thread.sleep(1);
}
@ -225,13 +226,13 @@ public class ThreadLimitHandlerTest
// let the other requests go
latch.countDown();
while (total.get() < 10 && System.nanoTime() < wait)
while (total.get() < 10 && NanoTime.secondsSince(start) < wait)
{
Thread.sleep(10);
}
assertThat(total.get(), is(10));
while (count.get() > 0 && System.nanoTime() < wait)
while (count.get() > 0 && NanoTime.secondsSince(start) < wait)
{
Thread.sleep(10);
}

View File

@ -13,7 +13,6 @@
package org.eclipse.jetty.server.session;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import javax.servlet.SessionCookieConfig;
import javax.servlet.http.HttpServletRequest;
@ -125,7 +124,7 @@ public class SessionCookieTest
mgr.setSessionCache(cache);
mgr.setSessionIdManager(idMgr);
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long now = System.currentTimeMillis();
Session session = new Session(mgr, new SessionData("123", "_foo", "0.0.0.0", now, now, now, 30));

View File

@ -115,7 +115,6 @@ public class SSLSelectChannelConnectorLoadTest
tasks[i] = threadPool.submit(workers[i]);
}
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
while (true)
{
Thread.sleep(1000);
@ -124,13 +123,9 @@ public class SSLSelectChannelConnectorLoadTest
{
done &= task.isDone();
}
//System.err.print("\rIterations: " + Worker.totalIterations.get() + "/" + clients * iterations);
if (done)
break;
}
long end = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
//System.err.println();
//System.err.println("Elapsed time: " + TimeUnit.MILLISECONDS.toSeconds(end - start) + "s");
for (Worker worker : workers)
{
@ -167,7 +162,6 @@ public class SSLSelectChannelConnectorLoadTest
tasks[i] = threadPool.submit(workers[i]);
}
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
while (true)
{
Thread.sleep(1000);
@ -176,13 +170,9 @@ public class SSLSelectChannelConnectorLoadTest
{
done &= task.isDone();
}
// System.err.print("\rIterations: " + Worker.totalIterations.get() + "/" + clients * iterations);
if (done)
break;
}
long end = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
// System.err.println();
// System.err.println("Elapsed time: " + TimeUnit.MILLISECONDS.toSeconds(end - start) + "s");
threadPool.shutdown();

View File

@ -43,9 +43,6 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
*
*/
public class SslUploadTest
{
private static Server server;
@ -118,7 +115,6 @@ public class SslUploadTest
}.start();
*/
long start = System.nanoTime();
OutputStream out = socket.getOutputStream();
out.write("POST / HTTP/1.1\r\n".getBytes());
out.write("Host: localhost\r\n".getBytes());
@ -136,10 +132,7 @@ public class SslUploadTest
InputStream in = socket.getInputStream();
String response = IO.toString(in);
assertTrue(response.indexOf("200") > 0);
// System.err.println(response);
// long end = System.nanoTime();
// System.out.println("upload time: " + TimeUnit.NANOSECONDS.toMillis(end - start));
assertEquals(requestContent.length, total);
}

View File

@ -18,7 +18,6 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContainerInitializer;
@ -27,6 +26,7 @@ import javax.servlet.ServletException;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -140,9 +140,9 @@ public class ServletContainerInitializerHolder extends BaseHolder<ServletContain
ctx.setExtendedListenerTypes(true);
if (LOG.isDebugEnabled())
{
long start = System.nanoTime();
long start = NanoTime.now();
initializer.onStartup(classes, ctx);
LOG.debug("ServletContainerInitializer {} called in {}ms", getClassName(), TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS));
LOG.debug("ServletContainerInitializer {} called in {}ms", getClassName(), NanoTime.millisSince(start));
}
else
initializer.onStartup(classes, ctx);

View File

@ -28,7 +28,6 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.servlet.GenericServlet;
import javax.servlet.MultipartConfigElement;
@ -50,6 +49,7 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ -1218,9 +1218,9 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
_unavailableStart = null;
else
{
long start = System.nanoTime();
long start = NanoTime.now();
while (start == 0)
start = System.nanoTime();
start = NanoTime.now();
_unavailableStart = new AtomicLong(start);
}
}
@ -1238,7 +1238,7 @@ public class ServletHolder extends Holder<Servlet> implements UserIdentity.Scope
{
long start = _unavailableStart.get();
if (start == 0 || System.nanoTime() - start < TimeUnit.SECONDS.toNanos(_unavailableException.getUnavailableSeconds()))
if (start == 0 || NanoTime.secondsSince(start) < _unavailableException.getUnavailableSeconds())
{
((HttpServletResponse)res).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}

View File

@ -51,6 +51,7 @@ import javax.servlet.http.HttpSessionEvent;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ -322,7 +323,7 @@ public class DoSFilter implements Filter
tracker = getRateTracker(request);
// Calculate the rate and check if it is over the allowed limit
final OverLimit overLimit = tracker.isRateExceeded(System.nanoTime());
final OverLimit overLimit = tracker.isRateExceeded(NanoTime.now());
// Pass it through if we are not currently over the rate limit.
if (overLimit == null)
@ -1196,11 +1197,9 @@ public class DoSFilter implements Filter
}
if (last == 0)
{
return null;
}
long rate = (now - last);
long rate = NanoTime.elapsed(last, now);
if (TimeUnit.NANOSECONDS.toSeconds(rate) < 1L)
{
return new Overage(Duration.ofNanos(rate), _maxRequestsPerSecond);
@ -1292,7 +1291,7 @@ public class DoSFilter implements Filter
int latestIndex = _next == 0 ? (_timestamps.length - 1) : (_next - 1);
long last = _timestamps[latestIndex];
boolean hasRecentRequest = last != 0 && TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - last) < 1L;
boolean hasRecentRequest = last != 0 && NanoTime.secondsSince(last) < 1L;
DoSFilter filter = (DoSFilter)_context.getAttribute(_filterName);

View File

@ -25,7 +25,6 @@ import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
@ -41,6 +40,7 @@ import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
@ -77,7 +77,7 @@ public class PushCacheFilter implements Filter
private final ConcurrentMap<String, PrimaryResource> _cache = new ConcurrentHashMap<>();
private long _associatePeriod = 4000L;
private int _maxAssociations = 16;
private long _renew = System.nanoTime();
private long _renew = NanoTime.now();
private boolean _useQueryInKey;
@Override
@ -125,7 +125,7 @@ public class PushCacheFilter implements Filter
return;
}
long now = System.nanoTime();
long now = NanoTime.now();
boolean conditional = false;
String referrer = null;
@ -184,10 +184,10 @@ public class PushCacheFilter implements Filter
PrimaryResource primaryResource = _cache.get(referrerPath);
if (primaryResource != null)
{
long primaryTimestamp = primaryResource._timestamp.get();
if (primaryTimestamp != 0)
long primaryNanoTime = primaryResource._nanoTime.get();
if (primaryNanoTime != 0)
{
if (now - primaryTimestamp < TimeUnit.MILLISECONDS.toNanos(_associatePeriod))
if (NanoTime.millisElapsed(primaryNanoTime, now) < _associatePeriod)
{
Set<String> associated = primaryResource._associated;
// Not strictly concurrent-safe, just best effort to limit associations.
@ -239,14 +239,14 @@ public class PushCacheFilter implements Filter
PrimaryResource r = new PrimaryResource();
primaryResource = _cache.putIfAbsent(path, r);
primaryResource = primaryResource == null ? r : primaryResource;
primaryResource._timestamp.compareAndSet(0, now);
primaryResource._nanoTime.compareAndSet(0, now);
if (LOG.isDebugEnabled())
LOG.debug("Cached primary resource {}", path);
}
else
{
long last = primaryResource._timestamp.get();
if (last < _renew && primaryResource._timestamp.compareAndSet(last, now))
long last = primaryResource._nanoTime.get();
if (NanoTime.isBefore(last, _renew) && primaryResource._nanoTime.compareAndSet(last, now))
{
primaryResource._associated.clear();
if (LOG.isDebugEnabled())
@ -301,7 +301,7 @@ public class PushCacheFilter implements Filter
@ManagedOperation(value = "Renews the push cache contents", impact = "ACTION")
public void renewPushCache()
{
_renew = System.nanoTime();
_renew = NanoTime.now();
}
@ManagedOperation(value = "Clears the push cache contents", impact = "ACTION")
@ -313,6 +313,6 @@ public class PushCacheFilter implements Filter
private static class PrimaryResource
{
private final Set<String> _associated = Collections.newSetFromMap(new ConcurrentHashMap<>());
private final AtomicLong _timestamp = new AtomicLong();
private final AtomicLong _nanoTime = new AtomicLong();
}
}

View File

@ -18,7 +18,6 @@ import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@ -34,6 +33,7 @@ import javax.servlet.http.PushBuilder;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.util.NanoTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -88,7 +88,7 @@ public class PushSessionCacheFilter implements Filter
@SuppressWarnings("unchecked")
ConcurrentHashMap<String, Long> timestamps = (ConcurrentHashMap<String, Long>)session.getAttribute(TIMESTAMP_ATTR);
Long last = timestamps.get(refererTarget._path);
if (last != null && TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - last) < _associateDelay)
if (last != null && NanoTime.millisSince(last) < _associateDelay)
{
if (refererTarget._associated.putIfAbsent(target._path, target) == null)
{
@ -138,7 +138,7 @@ public class PushSessionCacheFilter implements Filter
timestamps = new ConcurrentHashMap<>();
session.setAttribute(TIMESTAMP_ATTR, timestamps);
}
timestamps.put(uri, System.nanoTime());
timestamps.put(uri, NanoTime.now());
// Push any associated resources.
PushBuilder builder = request.newPushBuilder();

View File

@ -19,7 +19,6 @@ import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.LocalConnector;
@ -28,6 +27,7 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@ -105,9 +105,9 @@ public class DataRateLimitedServletTest
}
}
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
String response = connector.getResponse("GET /context/stream/content.txt HTTP/1.0\r\n\r\n");
long duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start;
long duration = NanoTime.millisSince(start);
assertThat("Response", response, containsString("200 OK"));
assertThat("Response Length", response.length(), greaterThan(1024 * 1024));

View File

@ -26,6 +26,7 @@ import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.servlets.DoSFilter.RateTracker;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.NanoTime;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -173,7 +174,7 @@ public class DoSFilterTest extends AbstractDoSFilterTest
for (int i = 0; i < 5; i++)
{
Thread.sleep(sleep);
if (rateTracker.isRateExceeded(System.nanoTime()) != null)
if (rateTracker.isRateExceeded(NanoTime.now()) != null)
exceeded = true;
}
return exceeded;

View File

@ -17,6 +17,7 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import javax.servlet.ServletException;
@ -305,8 +306,8 @@ public class GzipDefaultServletTest extends AbstractGzipTest
request.setHeader("Host", "tester");
request.setHeader("Connection", "close");
request.setHeader("Accept-Encoding", "gzip");
long fourSecondsAgo = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - 4000;
request.setHeader("If-Modified-Since", DateGenerator.formatDate(fourSecondsAgo));
Instant fourSecondsAgo = Instant.now().minusSeconds(4);
request.setHeader("If-Modified-Since", DateGenerator.formatDate(fourSecondsAgo.toEpochMilli()));
request.setURI("/context/file.txt");
// Issue request

View File

@ -14,8 +14,8 @@
package org.eclipse.jetty.util.ajax;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -40,7 +40,7 @@ public class JSONPojoConvertorFactoryTest
jsonIn.addConvertor(Enum.class, new JSONEnumConvertor());
Foo foo = new Foo();
foo.setName("Foo @ " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()));
foo.setName("Foo @ " + NanoTime.now());
foo.setInt1(1);
foo.setInt2(2);
foo.setLong1(1000001L);
@ -83,7 +83,7 @@ public class JSONPojoConvertorFactoryTest
jsonIn.addConvertor(Enum.class, new JSONEnumConvertor());
Foo foo = new Foo();
foo.setName("Foo @ " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()));
foo.setName("Foo @ " + NanoTime.now());
foo.setInt1(1);
foo.setInt2(2);
foo.setLong1(1000001L);

View File

@ -13,8 +13,7 @@
package org.eclipse.jetty.util.ajax;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -36,7 +35,7 @@ public class JSONPojoConvertorTest
json.addConvertor(Baz.class, new JSONPojoConvertor(Baz.class));
Foo foo = new Foo();
foo.setName("Foo @ " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()));
foo.setName("Foo @ " + NanoTime.now());
foo.setInt1(1);
foo.setInt2(2);
foo.setLong1(1000001L);
@ -76,7 +75,7 @@ public class JSONPojoConvertorTest
json.addConvertor(Baz.class, new JSONPojoConvertor(Baz.class, new String[]{"boolean2"}));
Foo foo = new Foo();
foo.setName("Foo @ " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime()));
foo.setName("Foo @ " + NanoTime.now());
foo.setInt1(1);
foo.setInt2(2);
foo.setLong1(1000001L);

View File

@ -0,0 +1,180 @@
//
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.util;
import java.util.concurrent.TimeUnit;
/**
* <p>Utility class with methods that deal with {@link System#nanoTime()}.</p>
*/
public class NanoTime
{
/**
* @return the current nanoTime via {@link System#nanoTime()}
*/
public static long now()
{
return System.nanoTime();
}
/**
* <p>Calculates the nanoseconds elapsed between two nanoTimes.</p>
*
* @param beginNanoTime the begin nanoTime
* @param endNanoTime the end nanoTime
* @return the nanoseconds elapsed
*/
public static long elapsed(long beginNanoTime, long endNanoTime)
{
return endNanoTime - beginNanoTime;
}
/**
* <p>Calculates the nanoseconds elapsed since a begin nanoTime and the current nanoTime.</p>
*
* @param beginNanoTime the begin nanoTime
* @return the nanoseconds elapsed since the given begin nanoTime and the current nanoTime
*/
public static long since(long beginNanoTime)
{
return elapsed(beginNanoTime, now());
}
/**
* <p>Calculates the nanoseconds remaining from the current nanoTime until an end nanoTime.</p>
*
* @param endNanoTime the end nanoTime
* @return the nanoseconds remaining from the current nanoTime until the given end nanoTime
*/
public static long until(long endNanoTime)
{
return elapsed(now(), endNanoTime);
}
/**
* <p>Calculates the milliseconds elapsed between two nanoTimes.</p>
*
* @param beginNanoTime the begin nanoTime
* @param endNanoTime the end nanoTime
* @return the milliseconds elapsed
*/
public static long millisElapsed(long beginNanoTime, long endNanoTime)
{
return TimeUnit.NANOSECONDS.toMillis(elapsed(beginNanoTime, endNanoTime));
}
/**
* <p>Calculates the milliseconds elapsed between a begin nanoTime and the current nanoTime.</p>
*
* @param beginNanoTime the begin nanoTime
* @return the milliseconds elapsed between the given begin nanoTime and the current nanoTime
*/
public static long millisSince(long beginNanoTime)
{
return millisElapsed(beginNanoTime, now());
}
/**
* <p>Calculates the milliseconds remaining between the current nanoTime and an end nanoTime.</p>
*
* @param endNanoTime the end nanoTime
* @return the milliseconds remaining between the current nanoTime and the given end nanoTime
*/
public static long millisUntil(long endNanoTime)
{
return millisElapsed(now(), endNanoTime);
}
/**
* <p>Calculates the seconds elapsed between two nanoTimes.</p>
*
* @param beginNanoTime the begin nanoTime
* @param endNanoTime the end nanoTime
* @return the seconds elapsed
*/
public static long secondsElapsed(long beginNanoTime, long endNanoTime)
{
return TimeUnit.NANOSECONDS.toSeconds(elapsed(beginNanoTime, endNanoTime));
}
/**
* <p>Calculates the seconds elapsed between a begin nanoTime and the current nanoTime.</p>
*
* @param beginNanoTime the begin nanoTime
* @return the seconds elapsed between the given begin nanoTime and the current nanoTime
*/
public static long secondsSince(long beginNanoTime)
{
return secondsElapsed(beginNanoTime, now());
}
/**
* <p>Calculates the seconds remaining between the current nanoTime and an end nanoTime.</p>
*
* @param endNanoTime the end nanoTime
* @return the seconds remaining between the current nanoTime and the given end nanoTime
*/
public static long secondsUntil(long endNanoTime)
{
return secondsElapsed(now(), endNanoTime);
}
/**
* <p>Returns whether the first nanoTime is strictly before the second nanoTime.</p>
* <p>Reads as: {@code "is nanoTime1 strictly before nanoTime2?"}.</p>
* <p>Avoids the common mistake of comparing the 2 nanoTimes with the
* less-than {@code <} operator, which cannot be used when comparing nanoTimes,
* as specified in {@link System#nanoTime()}.</p>
*
* @param nanoTime1 the first nanoTime
* @param nanoTime2 the second nanoTime
* @return whether the first nanoTime is strictly before the second nanoTime
* @see #isBeforeOrSame(long, long)
*/
public static boolean isBefore(long nanoTime1, long nanoTime2)
{
return nanoTime1 - nanoTime2 < 0;
}
/**
* <p>Returns whether the first nanoTime is before or the same as the second nanoTime.</p>
*
* @param nanoTime1 the first nanoTime
* @param nanoTime2 the second nanoTime
* @return whether the first nanoTime is before or the same as the second nanoTime
* @see #isBefore(long, long)
*/
public static boolean isBeforeOrSame(long nanoTime1, long nanoTime2)
{
return nanoTime1 - nanoTime2 <= 0;
}
/**
* <p>Spin waits for the specified number of nanoseconds.</p>
*
* @param nanos the amount of nanoseconds to spin wait
*/
public static void spinWait(long nanos)
{
long start = now();
while (since(start) < nanos)
{
Thread.onSpinWait();
}
}
private NanoTime()
{
}
}

View File

@ -114,7 +114,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
public void setPauseUntil(long time)
{
if (time > pauseUntil)
if (NanoTime.isBefore(pauseUntil, time))
pauseUntil = time;
}
@ -122,7 +122,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
{
if (pauseUntil == 0)
return false;
if (pauseUntil > now)
if (NanoTime.isBefore(now, pauseUntil))
{
if (LOG.isDebugEnabled())
LOG.debug("PAUSED {}", this);
@ -494,32 +494,28 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
}
}
public static enum DirAction
public enum DirAction
{
IGNORE, WATCH, ENTER;
IGNORE, WATCH, ENTER
}
/**
* Listener for path change events
*/
public static interface Listener extends EventListener
public interface Listener extends EventListener
{
void onPathWatchEvent(PathWatchEvent event);
}
/**
* EventListListener
*
* Listener that reports accumulated events in one shot
*/
public static interface EventListListener extends EventListener
public interface EventListListener extends EventListener
{
void onPathWatchEvents(List<PathWatchEvent> events);
}
/**
* PathWatchEvent
*
* Represents a file event. Reported to registered listeners.
*/
public class PathWatchEvent
@ -536,7 +532,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
this.path = path;
this.type = type;
this.config = config;
checked = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
checked = NanoTime.now();
check();
}
@ -565,7 +561,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
this.type = PathWatchEventType.UNKNOWN;
}
this.config = config;
checked = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
checked = NanoTime.now();
check();
}
@ -599,7 +595,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
check();
if (lastModified == modified && lastLength == length)
return (now - checked) >= quietTime;
return NanoTime.elapsed(checked, now) >= quietTime;
checked = now;
return false;
@ -607,7 +603,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
public long toQuietCheck(long now, long quietTime)
{
long check = quietTime - (now - checked);
long check = quietTime - NanoTime.elapsed(checked, now);
if (check <= 0)
return quietTime;
return check;
@ -615,10 +611,10 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
public void modified()
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long now = NanoTime.now();
checked = now;
check();
config.setPauseUntil(now + getUpdateQuietTimeMillis());
config.setPauseUntil(now + getUpdateQuietTimeNanos());
}
@Override
@ -683,13 +679,11 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
}
/**
* PathWatchEventType
*
* Type of an event
*/
public static enum PathWatchEventType
public enum PathWatchEventType
{
ADDED, DELETED, MODIFIED, UNKNOWN;
ADDED, DELETED, MODIFIED, UNKNOWN
}
private static final boolean IS_WINDOWS;
@ -853,7 +847,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
this.watchService = FileSystems.getDefault().newWatchService();
//ensure setting of quiet time is appropriate now we have a watcher
setUpdateQuietTime(getUpdateQuietTimeMillis(), TimeUnit.MILLISECONDS);
setUpdateQuietTime(getUpdateQuietTimeNanos(), TimeUnit.NANOSECONDS);
// Register all watched paths, walking dir hierarchies as needed, possibly generating
// fake add events if notifyExistingOnStart is true
@ -922,14 +916,9 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
return listeners.iterator();
}
/**
* Change the quiet time.
*
* @return the quiet time in millis
*/
public long getUpdateQuietTimeMillis()
long getUpdateQuietTimeNanos()
{
return TimeUnit.MILLISECONDS.convert(updateQuietTimeDuration, updateQuietTimeUnit);
return TimeUnit.NANOSECONDS.convert(updateQuietTimeDuration, updateQuietTimeUnit);
}
private void registerTree(Path dir, Config config, boolean notify) throws IOException
@ -1039,8 +1028,6 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
* single MODIFY event. Both the accumulation of events and coalescing of MODIFY
* events reduce the number and frequency of event reporting for "noisy" files (ie
* those that are undergoing rapid change).
*
* @see java.lang.Runnable#run()
*/
@Override
public void run()
@ -1051,7 +1038,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
LOG.debug("Starting java.nio file watching with {}", watchService);
}
long waitTime = getUpdateQuietTimeMillis();
long waitTime = getUpdateQuietTimeNanos();
WatchService watch = watchService;
@ -1063,7 +1050,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
try
{
// Reset all keys before watching
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long now = NanoTime.now();
for (Map.Entry<WatchKey, Config> e : keys.entrySet())
{
WatchKey k = e.getKey();
@ -1081,7 +1068,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
if (LOG.isDebugEnabled())
LOG.debug("Waiting for poll({})", waitTime);
key = waitTime < 0 ? watch.take() : waitTime > 0 ? watch.poll(waitTime, updateQuietTimeUnit) : watch.poll();
key = waitTime < 0 ? watch.take() : waitTime > 0 ? watch.poll(waitTime, TimeUnit.NANOSECONDS) : watch.poll();
// handle all active keys
while (key != null)
@ -1218,7 +1205,7 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
if (LOG.isDebugEnabled())
LOG.debug("processPending> {}", pending.values());
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long now = NanoTime.now();
long wait = Long.MAX_VALUE;
// pending map is maintained in LRU order
@ -1230,7 +1217,8 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
continue;
// if the path is quiet move to events
if (event.isQuiet(now, getUpdateQuietTimeMillis()))
long quietTime = getUpdateQuietTimeNanos();
if (event.isQuiet(now, quietTime))
{
if (LOG.isDebugEnabled())
LOG.debug("isQuiet {}", event);
@ -1239,11 +1227,11 @@ public class PathWatcher extends AbstractLifeCycle implements Runnable
}
else
{
long msToCheck = event.toQuietCheck(now, getUpdateQuietTimeMillis());
long nsToCheck = event.toQuietCheck(now, quietTime);
if (LOG.isDebugEnabled())
LOG.debug("pending {} {}", event, msToCheck);
if (msToCheck < wait)
wait = msToCheck;
LOG.debug("pending {} {}", event, nsToCheck);
if (nsToCheck < wait)
wait = nsToCheck;
}
}
if (LOG.isDebugEnabled())

View File

@ -161,11 +161,10 @@ public interface SocketAddressResolver
try
{
long start = System.nanoTime();
long start = NanoTime.now();
InetAddress[] addresses = InetAddress.getAllByName(host);
long elapsed = System.nanoTime() - start;
if (LOG.isDebugEnabled())
LOG.debug("Resolved {} in {} ms", host, TimeUnit.NANOSECONDS.toMillis(elapsed));
LOG.debug("Resolved {} in {} ms", host, NanoTime.millisSince(start));
List<InetSocketAddress> result = new ArrayList<>(addresses.length);
for (InetAddress address : addresses)

View File

@ -13,17 +13,18 @@
package org.eclipse.jetty.util.statistic;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import org.eclipse.jetty.util.NanoTime;
/**
* Counts the rate that {@link Long}s are added to this from the time of creation or the last call to {@link #reset()}.
*/
public class RateCounter
{
private final LongAdder _total = new LongAdder();
private final AtomicLong _timeStamp = new AtomicLong(System.nanoTime());
private final AtomicLong _nanoTime = new AtomicLong(NanoTime.now());
public void add(long l)
{
@ -32,13 +33,13 @@ public class RateCounter
public long getRate()
{
long elapsed = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - _timeStamp.get());
long elapsed = NanoTime.millisSince(_nanoTime.get());
return elapsed == 0 ? 0 : _total.sum() * 1000 / elapsed;
}
public void reset()
{
_timeStamp.getAndSet(System.nanoTime());
_nanoTime.set(NanoTime.now());
_total.reset();
}
}

View File

@ -18,6 +18,7 @@ import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.thread.AutoLock;
/**
@ -69,14 +70,13 @@ public class RateStatistic
private void update()
{
update(System.nanoTime());
update(NanoTime.now());
}
private void update(long now)
{
long expire = now - _nanoPeriod;
Long head = _samples.peekFirst();
while (head != null && head < expire)
while (head != null && NanoTime.elapsed(head, now) > _nanoPeriod)
{
_samples.removeFirst();
head = _samples.peekFirst();
@ -104,7 +104,7 @@ public class RateStatistic
*/
public int record()
{
long now = System.nanoTime();
long now = NanoTime.now();
try (AutoLock l = _lock.lock())
{
_count++;
@ -151,7 +151,7 @@ public class RateStatistic
Long head = _samples.peekFirst();
if (head == null)
return -1;
return units.convert(System.nanoTime() - head, TimeUnit.NANOSECONDS);
return units.convert(NanoTime.since(head), TimeUnit.NANOSECONDS);
}
}
@ -173,11 +173,11 @@ public class RateStatistic
public String dump(TimeUnit units)
{
long now = System.nanoTime();
long now = NanoTime.now();
try (AutoLock l = _lock.lock())
{
String samples = _samples.stream()
.mapToLong(t -> units.convert(now - t, TimeUnit.NANOSECONDS))
.mapToLong(t -> units.convert(NanoTime.elapsed(t, now), TimeUnit.NANOSECONDS))
.mapToObj(Long::toString)
.collect(Collectors.joining(System.lineSeparator()));
return String.format("%s%n%s", toString(now), samples);
@ -187,7 +187,7 @@ public class RateStatistic
@Override
public String toString()
{
return toString(System.nanoTime());
return toString(NanoTime.now());
}
private String toString(long nanoTime)

View File

@ -16,6 +16,7 @@ package org.eclipse.jetty.util.thread;
import java.util.concurrent.BlockingQueue;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
@ -56,24 +57,24 @@ public class MonitoredQueuedThreadPool extends QueuedThreadPool
public void execute(final Runnable job)
{
queueStats.increment();
long begin = System.nanoTime();
long begin = NanoTime.now();
super.execute(new Runnable()
{
@Override
public void run()
{
long queueLatency = System.nanoTime() - begin;
long queueLatency = NanoTime.since(begin);
queueStats.decrement();
threadStats.increment();
queueLatencyStats.record(queueLatency);
long start = System.nanoTime();
long start = NanoTime.now();
try
{
job.run();
}
finally
{
long taskLatency = System.nanoTime() - start;
long taskLatency = NanoTime.since(start);
threadStats.decrement();
taskLatencyStats.record(taskLatency);
}

View File

@ -27,6 +27,7 @@ import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.util.AtomicBiInteger;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.VirtualThreads;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
@ -216,7 +217,7 @@ public class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor
}
addBean(_tryExecutor);
_lastShrink.set(System.nanoTime());
_lastShrink.set(NanoTime.now());
super.doStart();
// The threads count set to MIN_VALUE is used to signal to Runners that the pool is stopped.
@ -249,7 +250,7 @@ public class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor
break;
// try to let jobs complete naturally for half our stop time
joinThreads(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout) / 2);
joinThreads(NanoTime.now() + TimeUnit.MILLISECONDS.toNanos(timeout) / 2);
// If we still have threads running, get a bit more aggressive
@ -264,7 +265,7 @@ public class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor
}
// wait again for the other half of our stop time
joinThreads(System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout) / 2);
joinThreads(NanoTime.now() + TimeUnit.MILLISECONDS.toNanos(timeout) / 2);
Thread.yield();
@ -323,7 +324,7 @@ public class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor
if (thread == Thread.currentThread())
continue;
long canWait = TimeUnit.NANOSECONDS.toMillis(stopByNanos - System.nanoTime());
long canWait = NanoTime.millisUntil(stopByNanos);
if (LOG.isDebugEnabled())
LOG.debug("Waiting for {} for {}", thread, canWait);
if (canWait <= 0)
@ -826,7 +827,7 @@ public class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor
if (LOG.isDebugEnabled())
LOG.debug("Starting {}", thread);
_threads.add(thread);
_lastShrink.set(System.nanoTime());
_lastShrink.set(NanoTime.now());
thread.start();
started = true;
}
@ -1050,8 +1051,8 @@ public class QueuedThreadPool extends ContainerLifeCycle implements ThreadFactor
if (idleTimeout > 0 && getThreads() > _minThreads)
{
long last = _lastShrink.get();
long now = System.nanoTime();
if ((now - last) > TimeUnit.MILLISECONDS.toNanos(idleTimeout) && _lastShrink.compareAndSet(last, now))
long now = NanoTime.now();
if (NanoTime.millisElapsed(last, now) > idleTimeout && _lastShrink.compareAndSet(last, now))
{
if (LOG.isDebugEnabled())
LOG.debug("shrinking {}", QueuedThreadPool.this);

View File

@ -25,6 +25,7 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import org.eclipse.jetty.util.AtomicBiInteger;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.ProcessorUtils;
import org.eclipse.jetty.util.VirtualThreads;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
@ -74,7 +75,7 @@ public class ReservedThreadExecutor extends AbstractLifeCycle implements TryExec
private final Set<ReservedThread> _threads = ConcurrentHashMap.newKeySet();
private final SynchronousQueue<Runnable> _queue = new SynchronousQueue<>(false);
private final AtomicBiInteger _count = new AtomicBiInteger(); // hi=pending; lo=size;
private final AtomicLong _lastEmptyTime = new AtomicLong(System.nanoTime());
private final AtomicLong _lastEmptyNanoTime = new AtomicLong(NanoTime.now());
private ThreadPoolBudget.Lease _lease;
private long _idleTimeNanos = DEFAULT_IDLE_TIMEOUT;
@ -247,7 +248,7 @@ public class ReservedThreadExecutor extends AbstractLifeCycle implements TryExec
if (size < 0 || pending + size >= _capacity)
return;
if (size == 0)
_lastEmptyTime.set(System.nanoTime());
_lastEmptyNanoTime.set(NanoTime.now());
if (!_count.compareAndSet(count, pending + 1, size))
continue;
@ -371,9 +372,9 @@ public class ReservedThreadExecutor extends AbstractLifeCycle implements TryExec
}
else
{
long now = System.nanoTime();
long lastEmpty = _lastEmptyTime.get();
if (size > 0 && _idleTimeNanos < (now - lastEmpty) && _lastEmptyTime.compareAndSet(lastEmpty, now))
long now = NanoTime.now();
long lastEmpty = _lastEmptyNanoTime.get();
if (size > 0 && _idleTimeNanos < NanoTime.elapsed(lastEmpty, now) && _lastEmptyNanoTime.compareAndSet(lastEmpty, now))
{
// it has been too long since we hit zero reserved threads, so are "busy" idle
next = State.IDLE;

View File

@ -242,23 +242,22 @@ public class BufferUtilTest
ThreadLocalRandom.current().nextBytes(bytes);
ByteBuffer buffer = BufferUtil.allocate(capacity);
BufferUtil.append(buffer, bytes, 0, capacity);
long startTest = System.nanoTime();
long startTest = NanoTime.now();
for (int i = 0; i < testRuns; i++)
{
long start = System.nanoTime();
long start = NanoTime.now();
for (int j = 0; j < iterations; j++)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
long startRun = System.nanoTime();
long startRun = NanoTime.now();
BufferUtil.writeTo(buffer.asReadOnlyBuffer(), out);
long elapsedRun = System.nanoTime() - startRun;
// LOG.warn("run elapsed={}ms", elapsedRun / 1000);
// LOG.info("run elapsed={}ms", NanoTime.elapsedFrom(startRun) / 1000);
assertThat("Bytes in out equal bytes in buffer", Arrays.equals(bytes, out.toByteArray()), is(true));
}
long elapsed = System.nanoTime() - start;
long elapsed = NanoTime.since(start);
LOG.warn("elapsed={}ms average={}ms", elapsed / 1000, elapsed / iterations / 1000);
}
LOG.warn("overall average: {}ms", (System.nanoTime() - startTest) / testRuns / iterations / 1000);
LOG.warn("overall average: {}ms", NanoTime.since(startTest) / testRuns / iterations / 1000);
}
@Test

View File

@ -25,12 +25,8 @@ import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Util meta Tests.
*/
public class DateCacheTest
{
@Test
@SuppressWarnings("ReferenceEquality")
public void testDateCache() throws Exception
@ -41,18 +37,17 @@ public class DateCacheTest
Thread.sleep(2000);
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long end = now + 3000;
String f = dc.formatNow(now);
String last = f;
Instant now = Instant.now();
Instant end = now.plusSeconds(3);
String f = dc.formatNow(now.toEpochMilli());
int hits = 0;
int misses = 0;
while (now < end)
while (now.isBefore(end))
{
last = f;
f = dc.formatNow(now);
String last = f;
f = dc.formatNow(now.toEpochMilli());
// System.err.printf("%s %s%n",f,last==f);
if (last == f)
hits++;
@ -60,7 +55,7 @@ public class DateCacheTest
misses++;
TimeUnit.MILLISECONDS.sleep(100);
now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
now = Instant.now();
}
assertThat(hits, Matchers.greaterThan(misses));
}

View File

@ -25,6 +25,7 @@ import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ -43,9 +44,9 @@ public class FutureCallbackTest
{
FutureCallback fcb = new FutureCallback();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
assertThrows(TimeoutException.class, () -> fcb.get(500, TimeUnit.MILLISECONDS));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.greaterThan(50L));
assertThat(NanoTime.millisSince(start), Matchers.greaterThan(50L));
}
@Test
@ -56,9 +57,9 @@ public class FutureCallbackTest
assertTrue(fcb.isDone());
assertFalse(fcb.isCancelled());
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
assertEquals(null, fcb.get());
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.lessThan(500L));
long start = NanoTime.now();
assertNull(fcb.get());
assertThat(NanoTime.millisSince(start), Matchers.lessThan(500L));
}
@Test
@ -82,10 +83,10 @@ public class FutureCallbackTest
}).start();
latch.await();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
assertEquals(null, fcb.get(10000, TimeUnit.MILLISECONDS));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.greaterThan(10L));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.lessThan(1000L));
long start = NanoTime.now();
assertNull(fcb.get(10000, TimeUnit.MILLISECONDS));
assertThat(NanoTime.millisSince(start), Matchers.greaterThan(10L));
assertThat(NanoTime.millisSince(start), Matchers.lessThan(1000L));
assertTrue(fcb.isDone());
assertFalse(fcb.isCancelled());
@ -100,11 +101,11 @@ public class FutureCallbackTest
assertTrue(fcb.isDone());
assertFalse(fcb.isCancelled());
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
ExecutionException e = assertThrows(ExecutionException.class, () -> fcb.get());
long start = NanoTime.now();
ExecutionException e = assertThrows(ExecutionException.class, fcb::get);
assertEquals(ex, e.getCause());
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.lessThan(100L));
assertThat(NanoTime.millisSince(start), Matchers.lessThan(100L));
}
@Test
@ -129,11 +130,11 @@ public class FutureCallbackTest
}).start();
latch.await();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
ExecutionException e = assertThrows(ExecutionException.class, () -> fcb.get(10000, TimeUnit.MILLISECONDS));
assertEquals(ex, e.getCause());
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.greaterThan(10L));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.lessThan(5000L));
assertThat(NanoTime.millisSince(start), Matchers.greaterThan(10L));
assertThat(NanoTime.millisSince(start), Matchers.lessThan(5000L));
assertTrue(fcb.isDone());
assertFalse(fcb.isCancelled());
@ -147,10 +148,10 @@ public class FutureCallbackTest
assertTrue(fcb.isDone());
assertTrue(fcb.isCancelled());
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
CancellationException e = assertThrows(CancellationException.class, () -> fcb.get());
long start = NanoTime.now();
CancellationException e = assertThrows(CancellationException.class, fcb::get);
assertThat(e.getCause(), Matchers.instanceOf(CancellationException.class));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.lessThan(100L));
assertThat(NanoTime.millisSince(start), Matchers.lessThan(100L));
}
@Test
@ -174,12 +175,12 @@ public class FutureCallbackTest
}).start();
latch.await();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
CancellationException e = assertThrows(CancellationException.class, () -> fcb.get(10000, TimeUnit.MILLISECONDS));
assertThat(e.getCause(), Matchers.instanceOf(CancellationException.class));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.greaterThan(10L));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, Matchers.lessThan(1000L));
assertThat(NanoTime.millisSince(start), Matchers.greaterThan(10L));
assertThat(NanoTime.millisSince(start), Matchers.lessThan(1000L));
assertTrue(fcb.isDone());
assertTrue(fcb.isCancelled());

View File

@ -49,9 +49,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(WorkDirExtension.class)
public class PathWatcherTest
{
public static final int QUIET_TIME;
public static final int WAIT_TIME;
public static final int LONG_TIME;
public static final long QUIET_TIME;
public static final long WAIT_TIME;
public static final long LONG_TIME;
static
{
@ -210,10 +210,10 @@ public class PathWatcherTest
{
//assertThat("Trigger Path must be set",triggerPath,notNullValue());
//assertThat("Trigger Type must be set",triggerType,notNullValue());
double multiplier = 25.0;
long awaitMillis = (long)((double)pathWatcher.getUpdateQuietTimeMillis() * multiplier);
LOG.debug("Waiting for finish ({} ms)", awaitMillis);
assertThat("Timed Out (" + awaitMillis + "ms) waiting for capture to finish", finishedLatch.await(awaitMillis, TimeUnit.MILLISECONDS), is(true));
long multiplier = 25;
long awaitNanos = pathWatcher.getUpdateQuietTimeNanos() * multiplier;
LOG.debug("Waiting for finish ({} ns)", awaitNanos);
assertThat("Timed Out (" + awaitNanos + "ns) waiting for capture to finish", finishedLatch.await(awaitNanos, TimeUnit.NANOSECONDS), is(true));
LOG.debug("Finished capture");
}
@ -246,7 +246,7 @@ public class PathWatcherTest
* @throws IOException if unable to write file
* @throws InterruptedException if sleep between writes was interrupted
*/
private void updateFileOverTime(Path path, int timeDuration, TimeUnit timeUnit)
private void updateFileOverTime(Path path, long timeDuration, TimeUnit timeUnit)
{
try
{
@ -257,11 +257,11 @@ public class PathWatcherTest
int chunkBufLen = 16;
byte[] chunkBuf = new byte[chunkBufLen];
Arrays.fill(chunkBuf, (byte)'x');
long end = System.nanoTime() + timeUnit.toNanos(timeDuration);
long start = NanoTime.now();
try (FileOutputStream out = new FileOutputStream(path.toFile()))
{
while (System.nanoTime() < end)
while (NanoTime.since(start) < timeUnit.toNanos(timeDuration))
{
out.write(chunkBuf);
out.flush();
@ -353,32 +353,32 @@ public class PathWatcherTest
// Check slow modification
capture.reset(1);
expected.clear();
long start = System.nanoTime();
long start = NanoTime.now();
new Thread(() ->
{
updateFileOverTime(dir.resolve("file1"), 2 * QUIET_TIME, TimeUnit.MILLISECONDS);
}).start();
expected.put("file1", new PathWatchEventType[]{MODIFIED});
capture.finishedLatch.await(LONG_TIME, TimeUnit.MILLISECONDS);
long end = System.nanoTime();
long end = NanoTime.now();
capture.assertEvents(expected);
assertThat(end - start, greaterThan(TimeUnit.MILLISECONDS.toNanos(2L * QUIET_TIME)));
assertThat(NanoTime.millisElapsed(start, end), greaterThan(2 * QUIET_TIME));
Thread.sleep(WAIT_TIME);
capture.assertEvents(expected);
// Check slow add
capture.reset(1);
expected.clear();
start = System.nanoTime();
start = NanoTime.now();
new Thread(() ->
{
updateFileOverTime(dir.resolve("file2"), 2 * QUIET_TIME, TimeUnit.MILLISECONDS);
}).start();
expected.put("file2", new PathWatchEventType[]{ADDED});
capture.finishedLatch.await(LONG_TIME, TimeUnit.MILLISECONDS);
end = System.nanoTime();
end = NanoTime.now();
capture.assertEvents(expected);
assertThat(end - start, greaterThan(TimeUnit.MILLISECONDS.toNanos(2 * QUIET_TIME)));
assertThat(NanoTime.millisElapsed(start, end), greaterThan(2 * QUIET_TIME));
Thread.sleep(WAIT_TIME);
capture.assertEvents(expected);
@ -951,15 +951,14 @@ public class PathWatcherTest
// New war added (slowly)
capture.setFinishTrigger(1);
Path warFile = dir.resolve("hello.war");
long start = System.nanoTime();
long start = NanoTime.now();
new Thread(() ->
{
updateFileOverTime(warFile, 2 * QUIET_TIME, TimeUnit.MILLISECONDS);
}).start();
assertTrue(capture.finishedLatch.await(4 * QUIET_TIME, TimeUnit.MILLISECONDS));
long end = System.nanoTime();
assertThat(end - start, greaterThan(TimeUnit.MILLISECONDS.toNanos(2 * QUIET_TIME)));
assertThat(NanoTime.millisSince(start), greaterThan(2 * QUIET_TIME));
Map<String, PathWatchEventType[]> expected = new HashMap<>();
expected.put("bar/WEB-INF/web.xml", new PathWatchEventType[]{ADDED});

View File

@ -120,10 +120,9 @@ public class QueueBenchmarkTest
}
await(barrier);
long begin = System.nanoTime();
long begin = NanoTime.now();
await(barrier);
long end = System.nanoTime();
long elapsed = TimeUnit.NANOSECONDS.toMillis(end - begin);
long elapsed = NanoTime.millisSince(begin);
logger.info("{} Readers/Writers: {}/{} => {} ms", queue.getClass().getSimpleName(), readers, writers, elapsed);
}
}

View File

@ -20,6 +20,7 @@ import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@ -409,7 +410,7 @@ public class ScannerTest
assertEquals(Notification.ADDED, event._notification);
// Create a new file by writing to it.
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long now = Instant.now().toEpochMilli();
File file = new File(_directory.toFile(), "st");
try (OutputStream out = new FileOutputStream(file, true))
{
@ -468,7 +469,7 @@ public class ScannerTest
{
File file = new File(_directory.toFile(), string);
if (file.exists())
file.setLastModified(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()));
file.setLastModified(Instant.now().toEpochMilli());
else
file.createNewFile();
}

View File

@ -54,10 +54,10 @@ public class SharedBlockingCallbackTest
try (Blocker blocker = sbcb.acquire())
{
blocker.succeeded();
start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
start = NanoTime.now();
blocker.block();
}
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, lessThan(500L));
assertThat(NanoTime.millisSince(start), lessThan(500L));
assertEquals(0, notComplete.get());
}
@ -88,11 +88,11 @@ public class SharedBlockingCallbackTest
}).start();
latch.await();
start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
start = NanoTime.now();
blocker.block();
}
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, greaterThan(10L));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, lessThan(1000L));
assertThat(NanoTime.millisSince(start), greaterThan(10L));
assertThat(NanoTime.millisSince(start), lessThan(1000L));
assertEquals(0, notComplete.get());
}
@ -112,10 +112,10 @@ public class SharedBlockingCallbackTest
}
catch (IOException e)
{
start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
start = NanoTime.now();
assertEquals(ex, e.getCause());
}
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, lessThan(100L));
assertThat(NanoTime.millisSince(start), lessThan(100L));
assertEquals(0, notComplete.get());
}
@ -150,7 +150,7 @@ public class SharedBlockingCallbackTest
}).start();
latch.await();
start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
start = NanoTime.now();
blocker.block();
}
fail("Should have thrown IOException");
@ -159,8 +159,8 @@ public class SharedBlockingCallbackTest
{
assertEquals(ex, e.getCause());
}
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, greaterThan(10L));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, lessThan(1000L));
assertThat(NanoTime.millisSince(start), greaterThan(10L));
assertThat(NanoTime.millisSince(start), lessThan(1000L));
assertEquals(0, notComplete.get());
}
@ -192,16 +192,16 @@ public class SharedBlockingCallbackTest
}).start();
latch.await();
long start = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = NanoTime.now();
try (Blocker blocker = sbcb.acquire())
{
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, greaterThan(10L));
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, lessThan(500L));
assertThat(NanoTime.millisSince(start), greaterThan(10L));
assertThat(NanoTime.millisSince(start), lessThan(500L));
blocker.succeeded();
blocker.block();
}
assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - start, lessThan(600L));
assertThat(NanoTime.millisSince(start), lessThan(600L));
assertEquals(0, notComplete.get());
}

View File

@ -13,9 +13,8 @@
package org.eclipse.jetty.util.component;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -56,7 +55,7 @@ public class LifeCycleListenerTest
assertTrue(listener.started, "The started event didn't occur");
// check that the starting event occurs before the started event
assertTrue(listener.startingTime <= listener.startedTime, "The starting event must occur before the started event");
assertTrue(NanoTime.isBeforeOrSame(listener.startingNanoTime, listener.startedNanoTime), "The starting event must occur before the started event");
// check that the lifecycle's state is started
assertTrue(lifecycle.isStarted(), "The lifecycle state is not started");
@ -98,7 +97,7 @@ public class LifeCycleListenerTest
assertTrue(listener.stopped, "The stopped event didn't occur");
// check that the stopping event occurs before the stopped event
assertTrue(listener.stoppingTime <= listener.stoppedTime, "The stopping event must occur before the stopped event");
assertTrue(NanoTime.isBeforeOrSame(listener.stoppingNanoTime, listener.stoppedNanoTime), "The stopping event must occur before the stopped event");
// System.out.println("STOPING TIME : " + listener.stoppingTime + " : " + listener.stoppedTime);
// check that the lifecycle's state is stopped
@ -150,7 +149,7 @@ public class LifeCycleListenerTest
}
}
private class TestListener extends AbstractLifeCycle.AbstractLifeCycleListener
private static class TestListener extends AbstractLifeCycle.AbstractLifeCycleListener
{
@SuppressWarnings("unused")
private boolean failure = false;
@ -159,10 +158,10 @@ public class LifeCycleListenerTest
private boolean stopped = false;
private boolean stopping = false;
private long startedTime;
private long startingTime;
private long stoppedTime;
private long stoppingTime;
private long startedNanoTime;
private long startingNanoTime;
private long stoppedNanoTime;
private long stoppingNanoTime;
private Throwable cause = null;
@ -180,13 +179,13 @@ public class LifeCycleListenerTest
public void lifeCycleStarted(LifeCycle event)
{
started = true;
startedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
startedNanoTime = NanoTime.now();
}
public void lifeCycleStarting(LifeCycle event)
{
starting = true;
startingTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
startingNanoTime = NanoTime.now();
// need to sleep to make sure the starting and started times are not
// the same
@ -203,13 +202,13 @@ public class LifeCycleListenerTest
public void lifeCycleStopped(LifeCycle event)
{
stopped = true;
stoppedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
stoppedNanoTime = NanoTime.now();
}
public void lifeCycleStopping(LifeCycle event)
{
stopping = true;
stoppingTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
stoppingNanoTime = NanoTime.now();
// need to sleep to make sure the stopping and stopped times are not
// the same

View File

@ -24,6 +24,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.thread.ThreadPool.SizedThreadPool;
import org.hamcrest.Matchers;
@ -677,19 +678,18 @@ public class QueuedThreadPoolTest extends AbstractThreadPoolTest
}
});
long beforeStop = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long beforeStop = NanoTime.now();
tp.stop();
long afterStop = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long afterStop = NanoTime.now();
assertTrue(tp.isStopped());
assertTrue(afterStop - beforeStop < 1000);
assertTrue(NanoTime.millisElapsed(beforeStop, afterStop) < 1000);
assertTrue(interruptedLatch.await(5, TimeUnit.SECONDS));
}
private void waitForIdle(QueuedThreadPool tp, int idle)
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = now;
while (tp.getIdleThreads() != idle && (now - start) < 10000)
long start = NanoTime.now();
while (tp.getIdleThreads() != idle && NanoTime.millisSince(start) < 10000)
{
try
{
@ -698,17 +698,15 @@ public class QueuedThreadPoolTest extends AbstractThreadPoolTest
catch (InterruptedException ignored)
{
}
now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
}
assertThat(tp.getIdleThreads(), is(idle));
}
private void waitForReserved(QueuedThreadPool tp, int reserved)
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = now;
long start = NanoTime.now();
ReservedThreadExecutor reservedThreadExecutor = tp.getBean(ReservedThreadExecutor.class);
while (reservedThreadExecutor.getAvailable() != reserved && (now - start) < 10000)
while (reservedThreadExecutor.getAvailable() != reserved && NanoTime.millisSince(start) < 10000)
{
try
{
@ -717,16 +715,14 @@ public class QueuedThreadPoolTest extends AbstractThreadPoolTest
catch (InterruptedException ignored)
{
}
now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
}
assertThat(reservedThreadExecutor.getAvailable(), is(reserved));
}
private void waitForThreads(QueuedThreadPool tp, int threads)
{
long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
long start = now;
while (tp.getThreads() != threads && (now - start) < 10000)
long start = NanoTime.now();
while (tp.getThreads() != threads && NanoTime.millisSince(start) < 10000)
{
try
{
@ -735,7 +731,6 @@ public class QueuedThreadPoolTest extends AbstractThreadPoolTest
catch (InterruptedException ignored)
{
}
now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
}
assertThat(tp.getThreads(), is(threads));
}

View File

@ -20,6 +20,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.util.NanoTime;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
@ -232,11 +233,10 @@ public class ReservedThreadExecutorTest
protected void waitForAvailable(int size) throws InterruptedException
{
long started = System.nanoTime();
long started = NanoTime.now();
while (_reservedExecutor.getAvailable() < size)
{
long elapsed = System.nanoTime() - started;
if (elapsed > TimeUnit.SECONDS.toNanos(10))
if (NanoTime.secondsSince(started) > 10)
fail("Took too long");
Thread.sleep(10);
}

View File

@ -22,6 +22,7 @@ import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.NanoTime;
import org.eclipse.jetty.websocket.core.CloseStatus;
import org.eclipse.jetty.websocket.core.CoreSession;
import org.eclipse.jetty.websocket.core.Frame;
@ -178,10 +179,10 @@ public class WebSocketServerTest extends WebSocketTester
BufferUtil.append(buffer, RawFrameBuilder.buildText("World", true), 0, 6 + 5);
client.getOutputStream().write(BufferUtil.toArray(buffer));
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
long start = NanoTime.now();
while (serverHandler.receivedFrames.size() < 3)
{
assertThat(System.nanoTime(), Matchers.lessThan(end));
assertThat(NanoTime.secondsSince(start), Matchers.lessThan(10L));
Thread.sleep(10);
}
assertThat(serverHandler.receivedFrames.size(), is(3));
@ -192,10 +193,10 @@ public class WebSocketServerTest extends WebSocketTester
BufferUtil.append(buffer, RawFrameBuilder.buildText("Bye", true), 0, 6 + 3);
client.getOutputStream().write(BufferUtil.toArray(buffer));
end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
start = NanoTime.now();
while (serverHandler.receivedFrames.size() < 5)
{
assertThat(System.nanoTime(), Matchers.lessThan(end));
assertThat(NanoTime.secondsSince(start), Matchers.lessThan(10L));
Thread.sleep(10);
}
assertThat(serverHandler.receivedFrames.size(), is(5));
@ -284,10 +285,10 @@ public class WebSocketServerTest extends WebSocketTester
BufferUtil.append(buffer, RawFrameBuilder.buildText("World", true), 0, 6 + 5);
client.getOutputStream().write(BufferUtil.toArray(buffer));
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
long start = NanoTime.now();
while (serverHandler.receivedFrames.size() < 3)
{
assertThat(System.nanoTime(), Matchers.lessThan(end));
assertThat(NanoTime.secondsSince(start), Matchers.lessThan(10L));
Thread.sleep(10);
}
assertThat(serverHandler.receivedFrames.size(), is(3));
@ -349,10 +350,10 @@ public class WebSocketServerTest extends WebSocketTester
BufferUtil.append(buffer, RawFrameBuilder.buildClose(CloseStatus.NORMAL_STATUS, true));
client.getOutputStream().write(BufferUtil.toArray(buffer));
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
long start = NanoTime.now();
while (serverHandler.receivedFrames.size() < 2)
{
assertThat(System.nanoTime(), Matchers.lessThan(end));
assertThat(NanoTime.secondsSince(start), Matchers.lessThan(10L));
Thread.sleep(10);
}
assertThat(serverHandler.receivedFrames.size(), is(2));
@ -416,10 +417,10 @@ public class WebSocketServerTest extends WebSocketTester
BufferUtil.append(buffer, RawFrameBuilder.buildClose(CloseStatus.NORMAL_STATUS, true));
client.getOutputStream().write(BufferUtil.toArray(buffer));
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
long start = NanoTime.now();
while (serverHandler.receivedFrames.size() < 2)
{
assertThat(System.nanoTime(), Matchers.lessThan(end));
assertThat(NanoTime.secondsSince(start), Matchers.lessThan(10L));
Thread.sleep(10);
}
assertThat(serverHandler.receivedFrames.size(), is(2));

Some files were not shown because too many files have changed in this diff Show More