1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.pool.impl;
19
20 import java.util.Timer;
21 import java.util.TimerTask;
22
23 /***
24 * <p>
25 * Provides a shared idle object eviction timer for all pools. This class wraps
26 * the standard {@link Timer} and keeps track of how many pools are using it.
27 * If no pools are using the timer, it is canceled. This prevents a thread
28 * being left running which, in application server environments, can lead to
29 * memory leads and/or prevent applications from shutting down or reloading
30 * cleanly.
31 * </p>
32 * <p>
33 * This class has package scope to prevent its inclusion in the pool public API.
34 * The class declaration below should *not* be changed to public.
35 * </p>
36 */
37 class EvictionTimer {
38 private static Timer _timer;
39 private static int _usageCount;
40
41 private EvictionTimer() {
42
43 }
44
45 /***
46 * Add the specified eviction task to the timer. Tasks that are added with a
47 * call to this method *must* call {@link #cancel(TimerTask)} to cancel the
48 * task to prevent memory and/or thread leaks in application server
49 * environments.
50 * @param task Task to be scheduled
51 * @param delay Delay in milliseconds before task is executed
52 * @param period Time in milliseconds between executions
53 */
54 static synchronized void schedule(TimerTask task, long delay, long period) {
55 if (null == _timer) {
56 _timer = new Timer(true);
57 }
58 _usageCount++;
59 _timer.schedule(task, delay, period);
60 }
61
62 /***
63 * Remove the specified eviction task from the timer.
64 * @param task Task to be scheduled
65 */
66 static synchronized void cancel(TimerTask task) {
67 task.cancel();
68 _usageCount--;
69 if (_usageCount == 0) {
70 _timer.cancel();
71 _timer = null;
72 }
73 }
74 }