/** * Creates a new tracker, which starts the stopwatch right now. */ public DeadlineTracker() { this(Stopwatch.createUnstarted()); }
public long getElapsedMillis() { return this.stopwatch.elapsed(TimeUnit.MILLISECONDS); }
/** * Creates a new tracker, using the specified stopwatch, and starts it right now. * The stopwatch is reset if it was already running. * @param stopwatch Specific Stopwatch to use */ public DeadlineTracker(Stopwatch stopwatch) { if (stopwatch.isRunning()) { stopwatch.reset(); } this.stopwatch = stopwatch.start(); }
@Override public String toString() { StringBuilder buf = new StringBuilder("DeadlineTracker(timeout="); buf.append(deadline); buf.append(", elapsed=").append(stopwatch.elapsed(TimeUnit.MILLISECONDS)); buf.append(")"); return buf.toString(); } }
/** * Check if we're already past the deadline. * @return true if we're past the deadline, otherwise false. Also returns false if no deadline * was specified */ public boolean timedOut() { if (!hasDeadline()) { return false; } return deadline - stopwatch.elapsed(TimeUnit.MILLISECONDS) <= 0; }
/** * Get the number of milliseconds before the deadline is reached. * <p> * This method is used to pass down the remaining deadline to the RPCs, so has special semantics. * A deadline of 0 is used to indicate an infinite deadline, and negative deadlines are invalid. * Thus, if the deadline has passed (i.e. <tt>deadline - stopwatch.elapsedMillis() <= 0</tt>), * the returned value is floored at <tt>1</tt>. * <p> * Callers who care about this behavior should first check {@link #timedOut()}. * * @return the remaining millis before the deadline is reached, or 1 if the remaining time is * lesser or equal to 0, or Long.MAX_VALUE if no deadline was specified (in which case it * should never be called). * @throws IllegalStateException if this method is called and no deadline was set */ public long getMillisBeforeDeadline() { if (!hasDeadline()) { throw new IllegalStateException("This tracker doesn't have a deadline set so it cannot " + "answer getMillisBeforeDeadline()"); } long millisBeforeDeadline = deadline - stopwatch.elapsed(TimeUnit.MILLISECONDS); millisBeforeDeadline = millisBeforeDeadline <= 0 ? 1 : millisBeforeDeadline; return millisBeforeDeadline; }