|
| 1 | +title: JDK中的timer正确的打开与关闭 |
| 2 | +tags: |
| 3 | + - Timer |
| 4 | +categories: |
| 5 | + - Dev |
| 6 | + - Java |
| 7 | +date: 2020-04-29 10:59:00 |
| 8 | +cover: true |
| 9 | +--- |
| 10 | + |
| 11 | + |
| 12 | +<!-- more --> |
| 13 | + |
| 14 | +## Timer和TimerTask |
| 15 | + |
| 16 | +Timer是jdk中提供的一个定时器工具,使用的时候会在主线程之外起一个单独的线程执行指定的计划任务,可以指定执行一次或者反复执行多次。 |
| 17 | + |
| 18 | +TimerTask是一个实现了Runnable接口的抽象类,代表一个可以被Timer执行的任务。 |
| 19 | + |
| 20 | +## Timer的调度 |
| 21 | +``` |
| 22 | +import java.util.Timer; |
| 23 | +import java.util.TimerTask; |
| 24 | +
|
| 25 | +public class TestTimer { |
| 26 | + |
| 27 | + public static void main(String args[]){ |
| 28 | + new Reminder(3); |
| 29 | + } |
| 30 | + |
| 31 | + public static class Reminder{ |
| 32 | + Timer timer; |
| 33 | + |
| 34 | + public Reminder(int sec){ |
| 35 | + timer = new Timer(); |
| 36 | + timer.schedule(new TimerTask(){ |
| 37 | + public void run(){ |
| 38 | + System.out.println("Time's up!"); |
| 39 | + timer.cancel(); |
| 40 | + System.out.println("Time's shutdown!"); |
| 41 | + } |
| 42 | + }, sec*1000); |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | +``` |
| 47 | +控制台输出 |
| 48 | +``` |
| 49 | +Time's up! |
| 50 | +Time's shutdown! |
| 51 | +``` |
| 52 | +从这个例子可以看出一个典型的利用timer执行计划任务的过程如下: |
| 53 | +* new一个TimerTask的子类,重写run方法来指定具体的任务,在这个例子里,我用匿名内部类的方式来实现了一个TimerTask的子类 |
| 54 | +* new一个Timer类,Timer的构造函数里会起一个单独的线程来执行计划任务。 |
| 55 | + |
| 56 | +jdk的实现代码如下: |
| 57 | +``` |
| 58 | +public Timer() { |
| 59 | + this("Timer-" + serialNumber()); |
| 60 | + } |
| 61 | +
|
| 62 | + public Timer(String name) { |
| 63 | + thread.setName(name); |
| 64 | + thread.start(); |
| 65 | + } |
| 66 | +``` |
| 67 | + |
| 68 | +## Timer的关闭 |
| 69 | +在JDK1.5以后,文档中有这么一句话: |
| 70 | +对 Timer 对象最后的引用完成后,并且 所有未处理的任务都已执行完成后,计时器的任务执行线程会正常终止(并且成为垃圾回收的对象)。但是这可能要很长时间后才发生。 |
| 71 | + |
| 72 | +### System.gc() |
| 73 | +系统默认当Timer运行结束后,如果没有手动终止,那么则只有当系统的垃圾收集被调用的时候才会对其进行回收终止。 |
| 74 | +因此,可以手动System.gc(); |
| 75 | +但是Sytem.gc()在一个项目中是不能随便调用的。因为一个tomcat只启动一个进程,而JVM的垃圾处理器也只有一个,所以在一个工程里运行System.gc也会影响到其他工程。 |
| 76 | + |
| 77 | +### cancle() |
| 78 | +首先看cancle方法的源码 |
| 79 | +``` |
| 80 | +public void cancel() { |
| 81 | + synchronized(queue) { |
| 82 | + thread.newTasksMayBeScheduled = false; |
| 83 | + queue.clear(); |
| 84 | + queue.notify(); // In case queue was already empty. |
| 85 | + } |
| 86 | + } |
| 87 | +``` |
| 88 | +没有显式的线程stop方法,而是调用了queue的clear方法和queue的notify方法,clear是个自定义方法,notify是Objec自带的方法,很明显是去唤醒wait方法的。 |
| 89 | + |
| 90 | +clear方法 |
| 91 | +``` |
| 92 | + /** |
| 93 | + * Removes all elements from the priority queue. |
| 94 | + */ |
| 95 | +void clear() { |
| 96 | + // Null out task references to prevent memory leak |
| 97 | + for (int i=1; i<=size; i++) |
| 98 | + queue[i] = null; |
| 99 | +
|
| 100 | + size = 0; |
| 101 | + } |
| 102 | +``` |
| 103 | +clear方法很简单,就是去清空queue,queue是一个TimerTask的数组,然后把queue的size重置成0,变成empty.还是没有看到显式的停止线程方法,回到最开始new Timer的时候,看看new Timer代码: |
| 104 | +``` |
| 105 | +public Timer() { |
| 106 | + this("Timer-" + serialNumber()); |
| 107 | + } |
| 108 | +
|
| 109 | + /** |
| 110 | + * Creates a new timer whose associated thread has the specified name. |
| 111 | + * The associated thread does <i>not</i> |
| 112 | + * {@linkplain Thread#setDaemon run as a daemon}. |
| 113 | + * |
| 114 | + * @param name the name of the associated thread |
| 115 | + * @throws NullPointerException if {@code name} is null |
| 116 | + * @since 1.5 |
| 117 | + */ |
| 118 | + public Timer(String name) { |
| 119 | + thread.setName(name); |
| 120 | + thread.start(); |
| 121 | + } |
| 122 | +``` |
| 123 | +看看这个内部变量thread: |
| 124 | +``` |
| 125 | + /** |
| 126 | + * The timer thread. |
| 127 | + */ |
| 128 | + private TimerThread thread = new TimerThread(queue); |
| 129 | +``` |
| 130 | +不是原生的Thread,是自定义的类TimerThread.这个类实现了Thread类,重写了run方法,如下: |
| 131 | +``` |
| 132 | +public void run() { |
| 133 | + try { |
| 134 | + mainLoop(); |
| 135 | + } finally { |
| 136 | + // Someone killed this Thread, behave as if Timer cancelled |
| 137 | + synchronized(queue) { |
| 138 | + newTasksMayBeScheduled = false; |
| 139 | + queue.clear(); // Eliminate obsolete references |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | +``` |
| 144 | +最后是这个mainLoop方法 |
| 145 | +``` |
| 146 | + /** |
| 147 | + * The main timer loop. (See class comment.) |
| 148 | + */ |
| 149 | + private void mainLoop() { |
| 150 | + while (true) { |
| 151 | + try { |
| 152 | + TimerTask task; |
| 153 | + boolean taskFired; |
| 154 | + synchronized(queue) { |
| 155 | + // Wait for queue to become non-empty |
| 156 | + while (queue.isEmpty() && newTasksMayBeScheduled) |
| 157 | + queue.wait(); |
| 158 | + if (queue.isEmpty()) |
| 159 | + break; // Queue is empty and will forever remain; die |
| 160 | +
|
| 161 | + // Queue nonempty; look at first evt and do the right thing |
| 162 | + long currentTime, executionTime; |
| 163 | + task = queue.getMin(); |
| 164 | + synchronized(task.lock) { |
| 165 | + if (task.state == TimerTask.CANCELLED) { |
| 166 | + queue.removeMin(); |
| 167 | + continue; // No action required, poll queue again |
| 168 | + } |
| 169 | + currentTime = System.currentTimeMillis(); |
| 170 | + executionTime = task.nextExecutionTime; |
| 171 | + if (taskFired = (executionTime<=currentTime)) { |
| 172 | + if (task.period == 0) { // Non-repeating, remove |
| 173 | + queue.removeMin(); |
| 174 | + task.state = TimerTask.EXECUTED; |
| 175 | + } else { // Repeating task, reschedule |
| 176 | + queue.rescheduleMin( |
| 177 | + task.period<0 ? currentTime - task.period |
| 178 | + : executionTime + task.period); |
| 179 | + } |
| 180 | + } |
| 181 | + } |
| 182 | + if (!taskFired) // Task hasn't yet fired; wait |
| 183 | + queue.wait(executionTime - currentTime); |
| 184 | + } |
| 185 | + if (taskFired) // Task fired; run it, holding no locks |
| 186 | + task.run(); |
| 187 | + } catch(InterruptedException e) { |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | +} |
| 192 | +``` |
| 193 | +可以看到wait方法,之前的notify就是通知到这个wait,然后clear方法在notify之前做了清空数组的操作,所以会break,线程执行结束,退出。 |
| 194 | + |
| 195 | +## Listener中的Timer |
| 196 | +很多业务中需要Timer一直执行,不会执行一次后就关闭,上面的例子中,timer调用cancel方法后,该timer就被关闭了。 |
| 197 | + |
| 198 | +监听器的实现方式有多种,这里我们说一下实现`ServletContextListener`接口。 |
| 199 | +该接口中有2个方法 |
| 200 | +``` |
| 201 | +public interface ServletContextListener extends EventListener { |
| 202 | + void contextInitialized(ServletContextEvent var1); |
| 203 | +
|
| 204 | + void contextDestroyed(ServletContextEvent var1); |
| 205 | +} |
| 206 | +``` |
| 207 | +即上下文的初始化和销毁。 |
| 208 | + |
| 209 | +我们来看一个实例 |
| 210 | +Listener |
| 211 | +``` |
| 212 | +public class MyListener implements ServletContextListener { |
| 213 | +
|
| 214 | + private Log log = LogFactory.getLog(MyListener.class); |
| 215 | +
|
| 216 | + @Override |
| 217 | + public void contextInitialized(ServletContextEvent servletContextEvent) { |
| 218 | + Timer timer = new Timer(); |
| 219 | + timer.schedule(new MyTask(),5000,5000); |
| 220 | + } |
| 221 | +
|
| 222 | + @Override |
| 223 | + public void contextDestroyed(ServletContextEvent servletContextEvent) { |
| 224 | + } |
| 225 | +} |
| 226 | +``` |
| 227 | +Task |
| 228 | +``` |
| 229 | +public class MyTask extends TimerTask { |
| 230 | +
|
| 231 | + @Override |
| 232 | + public void run() { |
| 233 | + System.out.println("timer 正在执行"); |
| 234 | + } |
| 235 | +} |
| 236 | +``` |
| 237 | +这样当程序启动的时候,在监听器的初始化中,timer会梅5秒执行一次 |
| 238 | +``` |
| 239 | +timer 正在执行 |
| 240 | +timer 正在执行 |
| 241 | +timer 正在执行 |
| 242 | +timer 正在执行 |
| 243 | +``` |
| 244 | +此次程序中我们没有去调用timer的cancel方法,这样会存在一个问题,就是产生的timer一直不会被关闭,就像上面说的只有当系统的垃圾收集被调用的时候才会对其进行回收终止。 |
| 245 | + |
| 246 | +同时tomcat日志会打印错误 |
| 247 | +``` |
| 248 | +28-Apr-2020 14:23:24.892 警告 [http-nio-8080-exec-23] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads Web应用程序[nyzft]似乎启动了一个名为[Timer-3]的线程,但未能停止它。这很可能会造成内存泄漏。线程的堆栈跟踪:[ |
| 249 | + java.lang.Object.wait(Native Method) |
| 250 | + java.lang.Object.wait(Object.java:502) |
| 251 | + java.util.TimerThread.mainLoop(Timer.java:526) |
| 252 | + java.util.TimerThread.run(Timer.java:505)] |
| 253 | +``` |
| 254 | +问题的原因就是我们没有手动去关闭timer,但是如果去调用cancel方法,真实的场景timer只会被执行一次,不符合业务要求。 |
| 255 | +因此可以通过listener的contextDestroyed去关闭timer |
| 256 | +``` |
| 257 | +public class MyListener implements ServletContextListener { |
| 258 | +
|
| 259 | + private Log log = LogFactory.getLog(MyListener.class); |
| 260 | +
|
| 261 | + private Timer timer; |
| 262 | +
|
| 263 | + @Override |
| 264 | + public void contextInitialized(ServletContextEvent servletContextEvent) { |
| 265 | + timer = new Timer(); |
| 266 | + timer.schedule(new MyTask(),5000,5000); |
| 267 | + System.out.println("执行"); |
| 268 | + } |
| 269 | +
|
| 270 | + @Override |
| 271 | + public void contextDestroyed(ServletContextEvent servletContextEvent) { |
| 272 | + timer.cancel(); |
| 273 | + System.out.println("关闭"); |
| 274 | + } |
| 275 | +} |
| 276 | +``` |
| 277 | +启动程序,过几秒钟后再关闭程序,查看控制台输出 |
| 278 | +``` |
| 279 | +执行 |
| 280 | +timer 正在执行 |
| 281 | +timer 正在执行 |
| 282 | +[2020-04-29 09:44:19,609] Artifact ssm-nyzft:war exploded: Artifact is deployed successfully |
| 283 | +[2020-04-29 09:44:19,609] Artifact ssm-nyzft:war exploded: Deploy took 38,550 milliseconds |
| 284 | +timer 正在执行 |
| 285 | +timer 正在执行 |
| 286 | +timer 正在执行 |
| 287 | +timer 正在执行 |
| 288 | +E:\Kit\Tomcat\tomcat8\apache-tomcat-8.5.39\bin\catalina.bat stop |
| 289 | +Disconnected from the target VM, address: '127.0.0.1:52706', transport: 'socket' |
| 290 | +Using CATALINA_BASE: "C:\Users\Administrator\.IntelliJIdea2019.1\system\tomcat\Unnamed_ssm-nyzft_2" |
| 291 | +Using CATALINA_HOME: "E:\Kit\Tomcat\tomcat8\apache-tomcat-8.5.39" |
| 292 | +Using CATALINA_TMPDIR: "E:\Kit\Tomcat\tomcat8\apache-tomcat-8.5.39\temp" |
| 293 | +Using JRE_HOME: "E:\Kit\JDK\JDK" |
| 294 | +Using CLASSPATH: "E:\Kit\Tomcat\tomcat8\apache-tomcat-8.5.39\bin\bootstrap.jar;E:\Kit\Tomcat\tomcat8\apache-tomcat-8.5.39\bin\tomcat-juli.jar" |
| 295 | +29-Apr-2020 09:44:40.511 淇℃伅 [main] org.apache.catalina.core.StandardServer.await A valid shutdown command was received via the shutdown port. Stopping the Server instance. |
| 296 | +29-Apr-2020 09:44:40.512 淇℃伅 [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-8081"] |
| 297 | +29-Apr-2020 09:44:40.638 淇℃伅 [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["ajp-nio-8009"] |
| 298 | +29-Apr-2020 09:44:40.750 淇℃伅 [main] org.apache.catalina.core.StandardService.stopInternal Stopping service [Catalina] |
| 299 | +关闭 |
| 300 | +``` |
| 301 | + |
| 302 | + |
| 303 | + |
| 304 | + |
| 305 | + |
0 commit comments