1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.util.thread;
20
21 import java.util.concurrent.BlockingQueue;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.ScheduledThreadPoolExecutor;
24 import java.util.concurrent.ThreadFactory;
25 import java.util.concurrent.TimeUnit;
26
27 import org.eclipse.jetty.util.component.AbstractLifeCycle;
28
29
30
31
32
33
34
35
36
37 public class ScheduledExecutorScheduler extends AbstractLifeCycle implements Scheduler
38 {
39 private final String name;
40 private final boolean daemon;
41 private volatile ScheduledThreadPoolExecutor scheduler;
42 private ClassLoader classloader;
43
44 public ScheduledExecutorScheduler()
45 {
46 this(null, false);
47 }
48
49 public ScheduledExecutorScheduler(String name, boolean daemon)
50 {
51 this (name,daemon, Thread.currentThread().getContextClassLoader());
52 }
53
54 public ScheduledExecutorScheduler(String name, boolean daemon, ClassLoader threadFactoryClassLoader)
55 {
56 this.name = name == null ? "Scheduler-" + hashCode() : name;
57 this.daemon = daemon;
58 this.classloader = threadFactoryClassLoader;
59 }
60
61 @Override
62 protected void doStart() throws Exception
63 {
64 scheduler = new ScheduledThreadPoolExecutor(1, new ThreadFactory()
65 {
66 @Override
67 public Thread newThread(Runnable r)
68 {
69 Thread thread = new Thread(r, name);
70 thread.setDaemon(daemon);
71 thread.setContextClassLoader(classloader);
72 return thread;
73 }
74 });
75 scheduler.setRemoveOnCancelPolicy(true);
76 super.doStart();
77 }
78
79
80
81 @Override
82 protected void doStop() throws Exception
83 {
84 scheduler.shutdownNow();
85 super.doStop();
86 scheduler = null;
87 }
88
89 @Override
90 public Task schedule(Runnable task, long delay, TimeUnit unit)
91 {
92 ScheduledFuture<?> result = scheduler.schedule(task, delay, unit);
93 return new ScheduledFutureTask(result);
94 }
95
96
97 private class ScheduledFutureTask implements Task
98 {
99 private final ScheduledFuture<?> scheduledFuture;
100
101 public ScheduledFutureTask(ScheduledFuture<?> scheduledFuture)
102 {
103 this.scheduledFuture = scheduledFuture;
104 }
105
106 @Override
107 public boolean cancel()
108 {
109 return scheduledFuture.cancel(false);
110 }
111 }
112 }