View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.pool2.impl;
18  
19  import java.lang.ref.WeakReference;
20  import java.security.AccessController;
21  import java.security.PrivilegedAction;
22  import java.time.Duration;
23  import java.util.HashMap;
24  import java.util.Map.Entry;
25  import java.util.concurrent.ScheduledFuture;
26  import java.util.concurrent.ScheduledThreadPoolExecutor;
27  import java.util.concurrent.ThreadFactory;
28  import java.util.concurrent.TimeUnit;
29  
30  
31  /**
32   * Provides a shared idle object eviction timer for all pools.
33   * <p>
34   * This class is currently implemented using {@link ScheduledThreadPoolExecutor}. This implementation may change in any
35   * future release. This class keeps track of how many pools are using it. If no pools are using the timer, it is
36   * cancelled. This prevents a thread being left running which, in application server environments, can lead to memory
37   * leads and/or prevent applications from shutting down or reloading cleanly.
38   * </p>
39   * <p>
40   * This class has package scope to prevent its inclusion in the pool public API. The class declaration below should
41   * *not* be changed to public.
42   * </p>
43   * <p>
44   * This class is intended to be thread-safe.
45   * </p>
46   *
47   * @since 2.0
48   */
49  class EvictionTimer {
50  
51      /**
52       * Thread factory that creates a daemon thread, with the context class loader from this class.
53       */
54      private static class EvictorThreadFactory implements ThreadFactory {
55  
56          @Override
57          public Thread newThread(final Runnable runnable) {
58              final Thread thread = new Thread(null, runnable, "commons-pool-evictor");
59              thread.setDaemon(true); // POOL-363 - Required for applications using Runtime.addShutdownHook().
60              AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
61                  thread.setContextClassLoader(EvictorThreadFactory.class.getClassLoader());
62                  return null;
63              });
64  
65              return thread;
66          }
67      }
68  
69      /**
70       * Task that removes references to abandoned tasks and shuts
71       * down the executor if there are no live tasks left.
72       */
73      private static class Reaper implements Runnable {
74          @Override
75          public void run() {
76              synchronized (EvictionTimer.class) {
77                  for (final Entry<WeakReference<BaseGenericObjectPool<?>.Evictor>, WeakRunner<BaseGenericObjectPool<?>.Evictor>> entry : TASK_MAP
78                          .entrySet()) {
79                      if (entry.getKey().get() == null) {
80                          executor.remove(entry.getValue());
81                          TASK_MAP.remove(entry.getKey());
82                      }
83                  }
84                  if (TASK_MAP.isEmpty() && executor != null) {
85                      executor.shutdown();
86                      executor.setCorePoolSize(0);
87                      executor = null;
88                  }
89              }
90          }
91      }
92  
93      /**
94       * Runnable that runs the referent of a weak reference. When the referent is no
95       * no longer reachable, run is no-op.
96       * @param <R> The kind of Runnable.
97       */
98      private static class WeakRunner<R extends Runnable> implements Runnable {
99  
100         private final WeakReference<R> ref;
101 
102         /**
103          * Constructs a new instance to track the given reference.
104          *
105          * @param ref the reference to track.
106          */
107         private WeakRunner(final WeakReference<R> ref) {
108            this.ref = ref;
109         }
110 
111         @Override
112         public void run() {
113             final Runnable task = ref.get();
114             if (task != null) {
115                 task.run();
116             } else {
117                 executor.remove(this);
118                 TASK_MAP.remove(ref);
119             }
120         }
121     }
122 
123 
124     /** Executor instance */
125     private static ScheduledThreadPoolExecutor executor; //@GuardedBy("EvictionTimer.class")
126 
127     /** Keys are weak references to tasks, values are runners managed by executor. */
128     private static final HashMap<
129         WeakReference<BaseGenericObjectPool<?>.Evictor>,
130         WeakRunner<BaseGenericObjectPool<?>.Evictor>> TASK_MAP = new HashMap<>(); // @GuardedBy("EvictionTimer.class")
131 
132     /**
133      * Removes the specified eviction task from the timer.
134      *
135      * @param evictor   Task to be cancelled.
136      * @param timeout   If the associated executor is no longer required, how
137      *                  long should this thread wait for the executor to
138      *                  terminate?
139      * @param restarting The state of the evictor.
140      */
141     static synchronized void cancel(final BaseGenericObjectPool<?>.Evictor evictor, final Duration timeout,
142             final boolean restarting) {
143         if (evictor != null) {
144             evictor.cancel();
145             remove(evictor);
146         }
147         if (!restarting && executor != null && TASK_MAP.isEmpty()) {
148             executor.shutdown();
149             try {
150                 executor.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS);
151             } catch (final InterruptedException e) {
152                 // Swallow
153                 // Significant API changes would be required to propagate this
154             }
155             executor.setCorePoolSize(0);
156             executor = null;
157         }
158     }
159 
160     /**
161      * For testing only.
162      *
163      * @return The executor.
164      */
165     static ScheduledThreadPoolExecutor getExecutor() {
166         return executor;
167     }
168 
169     /**
170      * @return the number of eviction tasks under management.
171      */
172     static synchronized int getNumTasks() {
173         return TASK_MAP.size();
174     }
175 
176     /**
177      * Gets the task map. Keys are weak references to tasks, values are runners managed by executor.
178      *
179      * @return the task map.
180      */
181     static HashMap<WeakReference<BaseGenericObjectPool<?>.Evictor>, WeakRunner<BaseGenericObjectPool<?>.Evictor>> getTaskMap() {
182         return TASK_MAP;
183     }
184 
185     /**
186      * Removes evictor from the task set and executor.
187      * Only called when holding the class lock.
188      *
189      * @param evictor Eviction task to remove
190      */
191     private static void remove(final BaseGenericObjectPool<?>.Evictor evictor) {
192         for (final Entry<WeakReference<BaseGenericObjectPool<?>.Evictor>, WeakRunner<BaseGenericObjectPool<?>.Evictor>> entry : TASK_MAP.entrySet()) {
193             if (entry.getKey().get() == evictor) {
194                 executor.remove(entry.getValue());
195                 TASK_MAP.remove(entry.getKey());
196                 break;
197             }
198         }
199     }
200 
201     /**
202      * Adds the specified eviction task to the timer. Tasks that are added with
203      * a call to this method *must* call {@link
204      * #cancel(BaseGenericObjectPool.Evictor, Duration, boolean)}
205      * to cancel the task to prevent memory and/or thread leaks in application
206      * server environments.
207      *
208      * @param task      Task to be scheduled.
209      * @param delay     Delay in milliseconds before task is executed.
210      * @param period    Time in milliseconds between executions.
211      */
212     static synchronized void schedule(
213             final BaseGenericObjectPool<?>.Evictor task, final Duration delay, final Duration period) {
214         if (null == executor) {
215             executor = new ScheduledThreadPoolExecutor(1, new EvictorThreadFactory());
216             executor.setRemoveOnCancelPolicy(true);
217             executor.scheduleAtFixedRate(new Reaper(), delay.toMillis(), period.toMillis(), TimeUnit.MILLISECONDS);
218         }
219         final WeakReference<BaseGenericObjectPool<?>.Evictor> ref = new WeakReference<>(task);
220         final WeakRunner<BaseGenericObjectPool<?>.Evictor> runner = new WeakRunner<>(ref);
221         final ScheduledFuture<?> scheduledFuture = executor.scheduleWithFixedDelay(runner, delay.toMillis(),
222                 period.toMillis(), TimeUnit.MILLISECONDS);
223         task.setScheduledFuture(scheduledFuture);
224         TASK_MAP.put(ref, runner);
225     }
226 
227     /** Prevents instantiation */
228     private EvictionTimer() {
229         // Hide the default constructor
230     }
231 
232     /**
233      * @since 2.4.3
234      */
235     @Override
236     public String toString() {
237         final StringBuilder builder = new StringBuilder();
238         builder.append("EvictionTimer []");
239         return builder.toString();
240     }
241 
242 }