001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.util.concurrent;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.util.concurrent.Futures.immediateCancelledFuture;
020import static com.google.common.util.concurrent.Internal.toNanosSaturated;
021import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
022import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
023import static java.util.Objects.requireNonNull;
024import static java.util.concurrent.TimeUnit.NANOSECONDS;
025
026import com.google.common.annotations.GwtIncompatible;
027import com.google.common.annotations.J2ktIncompatible;
028import com.google.errorprone.annotations.CanIgnoreReturnValue;
029import com.google.errorprone.annotations.concurrent.GuardedBy;
030import com.google.j2objc.annotations.WeakOuter;
031import java.time.Duration;
032import java.util.concurrent.Callable;
033import java.util.concurrent.Executor;
034import java.util.concurrent.Executors;
035import java.util.concurrent.Future;
036import java.util.concurrent.ScheduledExecutorService;
037import java.util.concurrent.ScheduledFuture;
038import java.util.concurrent.ThreadFactory;
039import java.util.concurrent.TimeUnit;
040import java.util.concurrent.TimeoutException;
041import java.util.concurrent.locks.ReentrantLock;
042import java.util.logging.Level;
043import org.jspecify.annotations.Nullable;
044
045/**
046 * Base class for services that can implement {@link #startUp} and {@link #shutDown} but while in
047 * the "running" state need to perform a periodic task. Subclasses can implement {@link #startUp},
048 * {@link #shutDown} and also a {@link #runOneIteration} method that will be executed periodically.
049 *
050 * <p>This class uses the {@link ScheduledExecutorService} returned from {@link #executor} to run
051 * the {@link #startUp} and {@link #shutDown} methods and also uses that service to schedule the
052 * {@link #runOneIteration} that will be executed periodically as specified by its {@link
053 * Scheduler}. When this service is asked to stop via {@link #stopAsync} it will cancel the periodic
054 * task (but not interrupt it) and wait for it to stop before running the {@link #shutDown} method.
055 *
056 * <p>Subclasses are guaranteed that the life cycle methods ({@link #runOneIteration}, {@link
057 * #startUp} and {@link #shutDown}) will never run concurrently. Notably, if any execution of {@link
058 * #runOneIteration} takes longer than its schedule defines, then subsequent executions may start
059 * late. Also, all life cycle methods are executed with a lock held, so subclasses can safely modify
060 * shared state without additional synchronization necessary for visibility to later executions of
061 * the life cycle methods.
062 *
063 * <h3>Usage Example</h3>
064 *
065 * <p>Here is a sketch of a service which crawls a website and uses the scheduling capabilities to
066 * rate limit itself.
067 *
068 * <pre>{@code
069 * class CrawlingService extends AbstractScheduledService {
070 *   private Set<Uri> visited;
071 *   private Queue<Uri> toCrawl;
072 *   protected void startUp() throws Exception {
073 *     toCrawl = readStartingUris();
074 *   }
075 *
076 *   protected void runOneIteration() throws Exception {
077 *     Uri uri = toCrawl.remove();
078 *     Collection<Uri> newUris = crawl(uri);
079 *     visited.add(uri);
080 *     for (Uri newUri : newUris) {
081 *       if (!visited.contains(newUri)) { toCrawl.add(newUri); }
082 *     }
083 *   }
084 *
085 *   protected void shutDown() throws Exception {
086 *     saveUris(toCrawl);
087 *   }
088 *
089 *   protected Scheduler scheduler() {
090 *     return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS);
091 *   }
092 * }
093 * }</pre>
094 *
095 * <p>This class uses the life cycle methods to read in a list of starting URIs and save the set of
096 * outstanding URIs when shutting down. Also, it takes advantage of the scheduling functionality to
097 * rate limit the number of queries we perform.
098 *
099 * @author Luke Sandberg
100 * @since 11.0
101 */
102@GwtIncompatible
103@J2ktIncompatible
104public abstract class AbstractScheduledService implements Service {
105  private static final LazyLogger logger = new LazyLogger(AbstractScheduledService.class);
106
107  /**
108   * A scheduler defines the policy for how the {@link AbstractScheduledService} should run its
109   * task.
110   *
111   * <p>Consider using the {@link #newFixedDelaySchedule} and {@link #newFixedRateSchedule} factory
112   * methods, these provide {@link Scheduler} instances for the common use case of running the
113   * service with a fixed schedule. If more flexibility is needed then consider subclassing {@link
114   * CustomScheduler}.
115   *
116   * @author Luke Sandberg
117   * @since 11.0
118   */
119  public abstract static class Scheduler {
120    /**
121     * Returns a {@link Scheduler} that schedules the task using the {@link
122     * ScheduledExecutorService#scheduleWithFixedDelay} method.
123     *
124     * @param initialDelay the time to delay first execution
125     * @param delay the delay between the termination of one execution and the commencement of the
126     *     next
127     * @since 33.4.0 (but since 28.0 in the JRE flavor)
128     */
129    @SuppressWarnings("Java7ApiChecker")
130    @IgnoreJRERequirement // Users will use this only if they're already using Duration
131    public static Scheduler newFixedDelaySchedule(Duration initialDelay, Duration delay) {
132      return newFixedDelaySchedule(
133          toNanosSaturated(initialDelay), toNanosSaturated(delay), NANOSECONDS);
134    }
135
136    /**
137     * Returns a {@link Scheduler} that schedules the task using the {@link
138     * ScheduledExecutorService#scheduleWithFixedDelay} method.
139     *
140     * @param initialDelay the time to delay first execution
141     * @param delay the delay between the termination of one execution and the commencement of the
142     *     next
143     * @param unit the time unit of the initialDelay and delay parameters
144     */
145    @SuppressWarnings("GoodTime") // should accept a java.time.Duration
146    public static Scheduler newFixedDelaySchedule(long initialDelay, long delay, TimeUnit unit) {
147      checkNotNull(unit);
148      checkArgument(delay > 0, "delay must be > 0, found %s", delay);
149      return new Scheduler() {
150        @Override
151        public Cancellable schedule(
152            AbstractService service, ScheduledExecutorService executor, Runnable task) {
153          return new FutureAsCancellable(
154              executor.scheduleWithFixedDelay(task, initialDelay, delay, unit));
155        }
156      };
157    }
158
159    /**
160     * Returns a {@link Scheduler} that schedules the task using the {@link
161     * ScheduledExecutorService#scheduleAtFixedRate} method.
162     *
163     * @param initialDelay the time to delay first execution
164     * @param period the period between successive executions of the task
165     * @since 33.4.0 (but since 28.0 in the JRE flavor)
166     */
167    @SuppressWarnings("Java7ApiChecker")
168    @IgnoreJRERequirement // Users will use this only if they're already using Duration
169    public static Scheduler newFixedRateSchedule(Duration initialDelay, Duration period) {
170      return newFixedRateSchedule(
171          toNanosSaturated(initialDelay), toNanosSaturated(period), NANOSECONDS);
172    }
173
174    /**
175     * Returns a {@link Scheduler} that schedules the task using the {@link
176     * ScheduledExecutorService#scheduleAtFixedRate} method.
177     *
178     * @param initialDelay the time to delay first execution
179     * @param period the period between successive executions of the task
180     * @param unit the time unit of the initialDelay and period parameters
181     */
182    @SuppressWarnings("GoodTime") // should accept a java.time.Duration
183    public static Scheduler newFixedRateSchedule(long initialDelay, long period, TimeUnit unit) {
184      checkNotNull(unit);
185      checkArgument(period > 0, "period must be > 0, found %s", period);
186      return new Scheduler() {
187        @Override
188        public Cancellable schedule(
189            AbstractService service, ScheduledExecutorService executor, Runnable task) {
190          return new FutureAsCancellable(
191              executor.scheduleAtFixedRate(task, initialDelay, period, unit));
192        }
193      };
194    }
195
196    /** Schedules the task to run on the provided executor on behalf of the service. */
197    abstract Cancellable schedule(
198        AbstractService service, ScheduledExecutorService executor, Runnable runnable);
199
200    private Scheduler() {}
201  }
202
203  /* use AbstractService for state management */
204  private final AbstractService delegate = new ServiceDelegate();
205
206  @WeakOuter
207  private final class ServiceDelegate extends AbstractService {
208
209    // A handle to the running task so that we can stop it when a shutdown has been requested.
210    // These two fields are volatile because their values will be accessed from multiple threads.
211    private volatile @Nullable Cancellable runningTask;
212    private volatile @Nullable ScheduledExecutorService executorService;
213
214    // This lock protects the task so we can ensure that none of the template methods (startUp,
215    // shutDown or runOneIteration) run concurrently with one another.
216    // TODO(lukes): why don't we use ListenableFuture to sequence things? Then we could drop the
217    // lock.
218    private final ReentrantLock lock = new ReentrantLock();
219
220    @WeakOuter
221    class Task implements Runnable {
222      @Override
223      public void run() {
224        lock.lock();
225        try {
226          /*
227           * requireNonNull is safe because Task isn't run (or at least it doesn't succeed in taking
228           * the lock) until after it's scheduled and the runningTask field is set.
229           */
230          if (requireNonNull(runningTask).isCancelled()) {
231            // task may have been cancelled while blocked on the lock.
232            return;
233          }
234          AbstractScheduledService.this.runOneIteration();
235        } catch (Throwable t) {
236          restoreInterruptIfIsInterruptedException(t);
237          try {
238            shutDown();
239          } catch (Exception ignored) {
240            restoreInterruptIfIsInterruptedException(ignored);
241            logger
242                .get()
243                .log(
244                    Level.WARNING,
245                    "Error while attempting to shut down the service after failure.",
246                    ignored);
247          }
248          notifyFailed(t);
249          // requireNonNull is safe now, just as it was above.
250          requireNonNull(runningTask).cancel(false); // prevent future invocations.
251        } finally {
252          lock.unlock();
253        }
254      }
255    }
256
257    private final Runnable task = new Task();
258
259    @Override
260    protected final void doStart() {
261      executorService =
262          MoreExecutors.renamingDecorator(executor(), () -> serviceName() + " " + state());
263      executorService.execute(
264          () -> {
265            lock.lock();
266            try {
267              startUp();
268              /*
269               * requireNonNull is safe because executorService is never cleared after the
270               * assignment above.
271               */
272              requireNonNull(executorService);
273              runningTask = scheduler().schedule(delegate, executorService, task);
274              notifyStarted();
275            } catch (Throwable t) {
276              restoreInterruptIfIsInterruptedException(t);
277              notifyFailed(t);
278              if (runningTask != null) {
279                // prevent the task from running if possible
280                runningTask.cancel(false);
281              }
282            } finally {
283              lock.unlock();
284            }
285          });
286    }
287
288    @Override
289    protected final void doStop() {
290      // Both requireNonNull calls are safe because doStop can run only after a successful doStart.
291      requireNonNull(runningTask);
292      requireNonNull(executorService);
293      runningTask.cancel(false);
294      executorService.execute(
295          () -> {
296            try {
297              lock.lock();
298              try {
299                if (state() != State.STOPPING) {
300                  // This means that the state has changed since we were scheduled. This implies
301                  // that an execution of runOneIteration has thrown an exception and we have
302                  // transitioned to a failed state, also this means that shutDown has already
303                  // been called, so we do not want to call it again.
304                  return;
305                }
306                shutDown();
307              } finally {
308                lock.unlock();
309              }
310              notifyStopped();
311            } catch (Throwable t) {
312              restoreInterruptIfIsInterruptedException(t);
313              notifyFailed(t);
314            }
315          });
316    }
317
318    @Override
319    public String toString() {
320      return AbstractScheduledService.this.toString();
321    }
322  }
323
324  /** Constructor for use by subclasses. */
325  protected AbstractScheduledService() {}
326
327  /**
328   * Run one iteration of the scheduled task. If any invocation of this method throws an exception,
329   * the service will transition to the {@link Service.State#FAILED} state and this method will no
330   * longer be called.
331   */
332  protected abstract void runOneIteration() throws Exception;
333
334  /**
335   * Start the service.
336   *
337   * <p>By default this method does nothing.
338   */
339  protected void startUp() throws Exception {}
340
341  /**
342   * Stop the service. This is guaranteed not to run concurrently with {@link #runOneIteration}.
343   *
344   * <p>By default this method does nothing.
345   */
346  protected void shutDown() throws Exception {}
347
348  /**
349   * Returns the {@link Scheduler} object used to configure this service. This method will only be
350   * called once.
351   */
352  // TODO(cpovirk): @ForOverride
353  protected abstract Scheduler scheduler();
354
355  /**
356   * Returns the {@link ScheduledExecutorService} that will be used to execute the {@link #startUp},
357   * {@link #runOneIteration} and {@link #shutDown} methods. If this method is overridden the
358   * executor will not be {@linkplain ScheduledExecutorService#shutdown shutdown} when this service
359   * {@linkplain Service.State#TERMINATED terminates} or {@linkplain Service.State#TERMINATED
360   * fails}. Subclasses may override this method to supply a custom {@link ScheduledExecutorService}
361   * instance. This method is guaranteed to only be called once.
362   *
363   * <p>By default this returns a new {@link ScheduledExecutorService} with a single thread pool
364   * that sets the name of the thread to the {@linkplain #serviceName() service name}. Also, the
365   * pool will be {@linkplain ScheduledExecutorService#shutdown() shut down} when the service
366   * {@linkplain Service.State#TERMINATED terminates} or {@linkplain Service.State#TERMINATED
367   * fails}.
368   */
369  protected ScheduledExecutorService executor() {
370    @WeakOuter
371    class ThreadFactoryImpl implements ThreadFactory {
372      @Override
373      public Thread newThread(Runnable runnable) {
374        return MoreExecutors.newThread(serviceName(), runnable);
375      }
376    }
377    ScheduledExecutorService executor =
378        Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl());
379    // Add a listener to shut down the executor after the service is stopped. This ensures that the
380    // JVM shutdown will not be prevented from exiting after this service has stopped or failed.
381    // Technically this listener is added after start() was called so it is a little gross, but it
382    // is called within doStart() so we know that the service cannot terminate or fail concurrently
383    // with adding this listener so it is impossible to miss an event that we are interested in.
384    addListener(
385        new Listener() {
386          @Override
387          public void terminated(State from) {
388            executor.shutdown();
389          }
390
391          @Override
392          public void failed(State from, Throwable failure) {
393            executor.shutdown();
394          }
395        },
396        directExecutor());
397    return executor;
398  }
399
400  /**
401   * Returns the name of this service. {@link AbstractScheduledService} may include the name in
402   * debugging output.
403   *
404   * @since 14.0
405   */
406  protected String serviceName() {
407    return getClass().getSimpleName();
408  }
409
410  @Override
411  public String toString() {
412    return serviceName() + " [" + state() + "]";
413  }
414
415  @Override
416  public final boolean isRunning() {
417    return delegate.isRunning();
418  }
419
420  @Override
421  public final State state() {
422    return delegate.state();
423  }
424
425  /**
426   * @since 13.0
427   */
428  @Override
429  public final void addListener(Listener listener, Executor executor) {
430    delegate.addListener(listener, executor);
431  }
432
433  /**
434   * @since 14.0
435   */
436  @Override
437  public final Throwable failureCause() {
438    return delegate.failureCause();
439  }
440
441  /**
442   * @since 15.0
443   */
444  @CanIgnoreReturnValue
445  @Override
446  public final Service startAsync() {
447    delegate.startAsync();
448    return this;
449  }
450
451  /**
452   * @since 15.0
453   */
454  @CanIgnoreReturnValue
455  @Override
456  public final Service stopAsync() {
457    delegate.stopAsync();
458    return this;
459  }
460
461  /**
462   * @since 15.0
463   */
464  @Override
465  public final void awaitRunning() {
466    delegate.awaitRunning();
467  }
468
469  /**
470   * @since 15.0
471   */
472  @Override
473  public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException {
474    delegate.awaitRunning(timeout, unit);
475  }
476
477  /**
478   * @since 15.0
479   */
480  @Override
481  public final void awaitTerminated() {
482    delegate.awaitTerminated();
483  }
484
485  /**
486   * @since 15.0
487   */
488  @Override
489  public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException {
490    delegate.awaitTerminated(timeout, unit);
491  }
492
493  interface Cancellable {
494    void cancel(boolean mayInterruptIfRunning);
495
496    boolean isCancelled();
497  }
498
499  private static final class FutureAsCancellable implements Cancellable {
500    private final Future<?> delegate;
501
502    FutureAsCancellable(Future<?> delegate) {
503      this.delegate = delegate;
504    }
505
506    @Override
507    @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller.
508    public void cancel(boolean mayInterruptIfRunning) {
509      delegate.cancel(mayInterruptIfRunning);
510    }
511
512    @Override
513    public boolean isCancelled() {
514      return delegate.isCancelled();
515    }
516  }
517
518  /**
519   * A {@link Scheduler} that provides a convenient way for the {@link AbstractScheduledService} to
520   * use a dynamically changing schedule. After every execution of the task, assuming it hasn't been
521   * cancelled, the {@link #getNextSchedule} method will be called.
522   *
523   * @author Luke Sandberg
524   * @since 11.0
525   */
526  public abstract static class CustomScheduler extends Scheduler {
527    /** Constructor for use by subclasses. */
528    public CustomScheduler() {}
529
530    /** A callable class that can reschedule itself using a {@link CustomScheduler}. */
531    private final class ReschedulableCallable implements Callable<@Nullable Void> {
532
533      /** The underlying task. */
534      private final Runnable wrappedRunnable;
535
536      /** The executor on which this Callable will be scheduled. */
537      private final ScheduledExecutorService executor;
538
539      /**
540       * The service that is managing this callable. This is used so that failure can be reported
541       * properly.
542       */
543      /*
544       * This reference is part of a reference cycle, which is typically something we want to avoid
545       * under j2objc -- but it is not detected by our j2objc cycle test. The cycle:
546       *
547       * - CustomScheduler.service contains an instance of ServiceDelegate. (It needs it so that it
548       *   can call notifyFailed.)
549       *
550       * - ServiceDelegate.runningTask contains an instance of ReschedulableCallable (at least in
551       *   the case that the service is using CustomScheduler). (It needs it so that it can cancel
552       *   the task and detect whether it has been cancelled.)
553       *
554       * - ReschedulableCallable has a reference back to its enclosing CustomScheduler. (It needs it
555       *   so that it can call getNextSchedule).
556       *
557       * Maybe there is a way to avoid this cycle. But we think the cycle is safe enough to ignore:
558       * Each task is retained for only as long as it is running -- so it's retained only as long as
559       * it would already be retained by the underlying executor.
560       *
561       * If the cycle test starts reporting this cycle in the future, we should add an entry to
562       * cycle_suppress_list.txt.
563       */
564      private final AbstractService service;
565
566      /**
567       * This lock is used to ensure safe and correct cancellation, it ensures that a new task is
568       * not scheduled while a cancel is ongoing. Also it protects the currentFuture variable to
569       * ensure that it is assigned atomically with being scheduled.
570       */
571      private final ReentrantLock lock = new ReentrantLock();
572
573      /** The future that represents the next execution of this task. */
574      @GuardedBy("lock")
575      private @Nullable SupplantableFuture cancellationDelegate;
576
577      ReschedulableCallable(
578          AbstractService service, ScheduledExecutorService executor, Runnable runnable) {
579        this.wrappedRunnable = runnable;
580        this.executor = executor;
581        this.service = service;
582      }
583
584      @Override
585      public @Nullable Void call() throws Exception {
586        wrappedRunnable.run();
587        reschedule();
588        return null;
589      }
590
591      /**
592       * Atomically reschedules this task and assigns the new future to {@link
593       * #cancellationDelegate}.
594       */
595      @CanIgnoreReturnValue
596      public Cancellable reschedule() {
597        // invoke the callback outside the lock, prevents some shenanigans.
598        Schedule schedule;
599        try {
600          schedule = CustomScheduler.this.getNextSchedule();
601        } catch (Throwable t) {
602          restoreInterruptIfIsInterruptedException(t);
603          service.notifyFailed(t);
604          return new FutureAsCancellable(immediateCancelledFuture());
605        }
606        // We reschedule ourselves with a lock held for two reasons. 1. we want to make sure that
607        // cancel calls cancel on the correct future. 2. we want to make sure that the assignment
608        // to currentFuture doesn't race with itself so that currentFuture is assigned in the
609        // correct order.
610        Throwable scheduleFailure = null;
611        Cancellable toReturn;
612        lock.lock();
613        try {
614          toReturn = initializeOrUpdateCancellationDelegate(schedule);
615        } catch (Throwable e) {
616          // Any Exception is either a RuntimeException or sneaky checked exception.
617          //
618          // If an exception is thrown by the subclass then we need to make sure that the service
619          // notices and transitions to the FAILED state. We do it by calling notifyFailed directly
620          // because the service does not monitor the state of the future so if the exception is not
621          // caught and forwarded to the service the task would stop executing but the service would
622          // have no idea.
623          // TODO(lukes): consider building everything in terms of ListenableScheduledFuture then
624          // the AbstractService could monitor the future directly. Rescheduling is still hard...
625          // but it would help with some of these lock ordering issues.
626          scheduleFailure = e;
627          toReturn = new FutureAsCancellable(immediateCancelledFuture());
628        } finally {
629          lock.unlock();
630        }
631        // Call notifyFailed outside the lock to avoid lock ordering issues.
632        if (scheduleFailure != null) {
633          service.notifyFailed(scheduleFailure);
634        }
635        return toReturn;
636      }
637
638      @GuardedBy("lock")
639      /*
640       * The GuardedBy checker warns us that we're not holding cancellationDelegate.lock. But in
641       * fact we are holding it because it is the same as this.lock, which we know we are holding,
642       * thanks to @GuardedBy above. (cancellationDelegate.lock is initialized to this.lock in the
643       * call to `new SupplantableFuture` below.)
644       */
645      @SuppressWarnings("GuardedBy")
646      private Cancellable initializeOrUpdateCancellationDelegate(Schedule schedule) {
647        if (cancellationDelegate == null) {
648          return cancellationDelegate = new SupplantableFuture(lock, submitToExecutor(schedule));
649        }
650        if (!cancellationDelegate.currentFuture.isCancelled()) {
651          cancellationDelegate.currentFuture = submitToExecutor(schedule);
652        }
653        return cancellationDelegate;
654      }
655
656      private ScheduledFuture<@Nullable Void> submitToExecutor(Schedule schedule) {
657        return executor.schedule(this, schedule.delay, schedule.unit);
658      }
659    }
660
661    /**
662     * Contains the most recently submitted {@code Future}, which may be cancelled or updated,
663     * always under a lock.
664     */
665    private static final class SupplantableFuture implements Cancellable {
666      private final ReentrantLock lock;
667
668      @GuardedBy("lock")
669      private Future<@Nullable Void> currentFuture;
670
671      SupplantableFuture(ReentrantLock lock, Future<@Nullable Void> currentFuture) {
672        this.lock = lock;
673        this.currentFuture = currentFuture;
674      }
675
676      @Override
677      @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller.
678      public void cancel(boolean mayInterruptIfRunning) {
679        /*
680         * Lock to ensure that a task cannot be rescheduled while a cancel is ongoing.
681         *
682         * In theory, cancel() could execute arbitrary listeners -- bad to do while holding a lock.
683         * However, we don't expose currentFuture to users, so they can't attach listeners. And the
684         * Future might not even be a ListenableFuture, just a plain Future. That said, similar
685         * problems can exist with methods like FutureTask.done(), not to mention slow calls to
686         * Thread.interrupt() (as discussed in InterruptibleTask). At the end of the day, it's
687         * unlikely that cancel() will be slow, so we can probably get away with calling it while
688         * holding a lock. Still, it would be nice to avoid somehow.
689         */
690        lock.lock();
691        try {
692          currentFuture.cancel(mayInterruptIfRunning);
693        } finally {
694          lock.unlock();
695        }
696      }
697
698      @Override
699      public boolean isCancelled() {
700        lock.lock();
701        try {
702          return currentFuture.isCancelled();
703        } finally {
704          lock.unlock();
705        }
706      }
707    }
708
709    @Override
710    final Cancellable schedule(
711        AbstractService service, ScheduledExecutorService executor, Runnable runnable) {
712      return new ReschedulableCallable(service, executor, runnable).reschedule();
713    }
714
715    /**
716     * A value object that represents an absolute delay until a task should be invoked.
717     *
718     * @author Luke Sandberg
719     * @since 11.0
720     */
721    protected static final class Schedule {
722
723      private final long delay;
724      private final TimeUnit unit;
725
726      /**
727       * @param delay the time from now to delay execution
728       * @param unit the time unit of the delay parameter
729       */
730      public Schedule(long delay, TimeUnit unit) {
731        this.delay = delay;
732        this.unit = checkNotNull(unit);
733      }
734
735      /**
736       * @param delay the time from now to delay execution
737       * @since 33.4.0 (but since 31.1 in the JRE flavor)
738       */
739      @SuppressWarnings("Java7ApiChecker")
740      @IgnoreJRERequirement // Users will use this only if they're already using Duration
741      public Schedule(Duration delay) {
742        this(toNanosSaturated(delay), NANOSECONDS);
743      }
744    }
745
746    /**
747     * Calculates the time at which to next invoke the task.
748     *
749     * <p>This is guaranteed to be called immediately after the task has completed an iteration and
750     * on the same thread as the previous execution of {@link
751     * AbstractScheduledService#runOneIteration}.
752     *
753     * @return a schedule that defines the delay before the next execution.
754     */
755    // TODO(cpovirk): @ForOverride
756    protected abstract Schedule getNextSchedule() throws Exception;
757  }
758}