View Javadoc
1   /*
2    * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
3    * Copyright (C) 2010  Mickael Guessant
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18   */
19  
20  package davmail.http;
21  
22  import org.apache.http.conn.HttpClientConnectionManager;
23  import org.apache.log4j.Logger;
24  
25  import java.util.Set;
26  import java.util.concurrent.ConcurrentHashMap;
27  import java.util.concurrent.Executors;
28  import java.util.concurrent.ScheduledExecutorService;
29  import java.util.concurrent.ThreadFactory;
30  import java.util.concurrent.TimeUnit;
31  import java.util.concurrent.atomic.AtomicInteger;
32  
33  /**
34   * Single thread for all connection managers.
35   * Close idle connections
36   */
37  public class DavMailIdleConnectionEvictor {
38      protected static final Logger LOGGER = Logger.getLogger(DavMailIdleConnectionEvictor.class);
39  
40      // Thread-safe set avoids needing coarse-grained synchronized blocks during socket cleanup
41      private static final Set<HttpClientConnectionManager> connectionManagers = ConcurrentHashMap.newKeySet();
42  
43      private static final long sleepTimeMs = 1000L * 60;
44      private static final long maxIdleTimeMs = 1000L * 60 * 5;
45  
46      private static ScheduledExecutorService scheduler = null;
47  
48      private static synchronized void initEvictorThread() {
49          if (scheduler == null) {
50              scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() {
51                  final AtomicInteger count = new AtomicInteger();
52                  @Override
53                  public Thread newThread(Runnable r) {
54                      Thread thread = new Thread(r, "PoolEvictor-" + count.getAndIncrement());
55                      thread.setDaemon(true);
56                      thread.setUncaughtExceptionHandler((t, e) -> LOGGER.error(e.getMessage(), e));
57                      return thread;
58                  }
59              });
60  
61              // use scheduleWithFixedDelay to avoid catchup wave on laptop wakeup from sleep
62              scheduler.scheduleWithFixedDelay(() -> {
63                  // Make sure thread never exits on error
64                  try {
65                      for (HttpClientConnectionManager connectionManager : connectionManagers) {
66                          try {
67                              connectionManager.closeExpiredConnections();
68                              if (maxIdleTimeMs > 0) {
69                                  connectionManager.closeIdleConnections(maxIdleTimeMs, TimeUnit.MILLISECONDS);
70                              }
71                          } catch (Exception e) {
72                              LOGGER.warn("Error closing idle connections on manager: " + e.getMessage(), e);
73                          }
74                      }
75                  } catch (Throwable t) {
76                      LOGGER.error("Unexpected error in connection pool evictor task", t);
77                  }
78              }, sleepTimeMs, sleepTimeMs, TimeUnit.MILLISECONDS);
79          }
80      }
81  
82      /**
83       * Shutdown the connection manager evictor thread.
84       * @throws InterruptedException on error
85       */
86      public static synchronized void shutdown() throws InterruptedException {
87          if (scheduler != null) {
88              scheduler.shutdown();
89              if (!scheduler.awaitTermination(sleepTimeMs, TimeUnit.MILLISECONDS)) {
90                  LOGGER.warn("Timed out waiting for tasks to complete");
91              }
92              // make sure we don't reuse old connection managers
93              connectionManagers.clear();
94              scheduler = null;
95          }
96      }
97  
98      /**
99       * Add a connection manager to the eviction monitor set.
100      * @param connectionManager connection manager to monitor
101      */
102     public static void addConnectionManager(HttpClientConnectionManager connectionManager) {
103         if (connectionManager != null) {
104             initEvictorThread();
105             connectionManagers.add(connectionManager);
106         }
107     }
108 
109     /**
110      * Remove the connection manager from the eviction monitor set.
111      * @param connectionManager connection manager to remove
112      */
113     public static void removeConnectionManager(HttpClientConnectionManager connectionManager) {
114         if (connectionManager != null) {
115             connectionManagers.remove(connectionManager);
116         }
117     }
118 }