2 // ========================================================================
3 // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.util.thread;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.ScheduledThreadPoolExecutor;
23 import java.util.concurrent.ThreadFactory;
24 import java.util.concurrent.TimeUnit;
26 import org.eclipse.jetty.util.component.AbstractLifeCycle;
29 * Implementation of {@link Scheduler} based on JDK's {@link ScheduledThreadPoolExecutor}.
31 * While use of {@link ScheduledThreadPoolExecutor} creates futures that will not be used,
32 * it has the advantage of allowing to set a property to remove cancelled tasks from its
33 * queue even if the task did not fire, which provides a huge benefit in the performance
34 * of garbage collection in young generation.
36 public class ScheduledExecutorScheduler extends AbstractLifeCycle implements Scheduler
38 private final String name;
39 private final boolean daemon;
40 private volatile ScheduledThreadPoolExecutor scheduler;
42 public ScheduledExecutorScheduler()
47 public ScheduledExecutorScheduler(String name, boolean daemon)
49 this.name = name == null ? "Scheduler-" + hashCode() : name;
54 protected void doStart() throws Exception
56 scheduler = new ScheduledThreadPoolExecutor(1, new ThreadFactory()
59 public Thread newThread(Runnable r)
61 Thread thread = new Thread(r, name);
62 thread.setDaemon(daemon);
66 scheduler.setRemoveOnCancelPolicy(true);
71 protected void doStop() throws Exception
73 scheduler.shutdownNow();
79 public Task schedule(Runnable task, long delay, TimeUnit unit)
81 ScheduledFuture<?> result = scheduler.schedule(task, delay, unit);
82 return new ScheduledFutureTask(result);
85 private class ScheduledFutureTask implements Task
87 private final ScheduledFuture<?> scheduledFuture;
89 public ScheduledFutureTask(ScheduledFuture<?> scheduledFuture)
91 this.scheduledFuture = scheduledFuture;
95 public boolean cancel()
97 return scheduledFuture.cancel(false);