package org.ektorp.http;

import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

import org.apache.http.conn.*;

public class IdleConnectionMonitor {

	private final static long DEFAULT_IDLE_CHECK_INTERVAL = 30;
	
	private final static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, new ThreadFactory() {
		
		private final AtomicInteger threadCount = new AtomicInteger(0);
		
		public Thread newThread(Runnable r) {
			Thread t = new Thread(r);
			t.setDaemon(true);
			t.setName(String.format("ektorp-idle-connection-monitor-thread-%s", threadCount.incrementAndGet()));
			return t;
		}
	});
	
	public static void monitor(ClientConnectionManager cm) {
		executorService.scheduleWithFixedDelay(new CleanupTask(cm), DEFAULT_IDLE_CHECK_INTERVAL, DEFAULT_IDLE_CHECK_INTERVAL, TimeUnit.SECONDS);
	}
	
	private static class CleanupTask implements Runnable {

		final ClientConnectionManager cm;
		
		CleanupTask(ClientConnectionManager cm) {
			this.cm = cm;
		}
		
		public void run() {
			cm.closeExpiredConnections();
		}
		
	}
	
}

@@ -19,16 +19,52 @@
 .http;%0A%0A
+import java.lang.ref.WeakReference;%0A
 import j
@@ -672,17 +672,20 @@
 %0A%09%7D);%0A%09%0A
-%09
+    
 public s
@@ -733,18 +733,114 @@
 r cm) %7B%0A
-%09%09
+        CleanupTask cleanupTask = new CleanupTask(cm);%0A        ScheduledFuture%3C?%3E cleanupFuture = 
 executor
@@ -870,21 +870,17 @@
 edDelay(
-new C
+c
 leanupTa
@@ -881,20 +881,16 @@
 anupTask
-(cm)
 , DEFAUL
@@ -916,57 +916,187 @@
 AL, 
-DEFAULT_IDLE_CHECK_INTERVAL, TimeUnit.SECONDS);%0A%09
+%0A                                                                                DEFAULT_IDLE_CHECK_INTERVAL, TimeUnit.SECONDS);%0A        cleanupTask.setFuture(cleanupFuture);%0A    
 %7D%0A%09%0A
@@ -1156,16 +1156,44 @@
  %7B%0A%0A
-%09%09final 
+        private final WeakReference%3C
 Clie
@@ -1215,141 +1215,521 @@
 ager
+%3E
  cm;%0A
-%09%09%0A%09%09CleanupTask(ClientConnectionManager cm) %7B%0A%09%09%09this.cm = 
+        private ScheduledFuture%3C?%3E thisFuture;%0A%0A        CleanupTask(ClientConnectionManager cm) %7B%0A            this.cm = new WeakReference%3CClientConnectionManager%3E(
 cm
+)
 ;%0A
-%09%09%7D%0A%09%09%0A%09%09public void run() %7B%0A%09%09%09cm.closeExpiredConnections();%0A%09%09
+        %7D%0A%0A        public void setFuture(ScheduledFuture%3C?%3E future) %7B%0A            thisFuture = future;%0A        %7D%0A%0A        public void run() %7B%0A            if (cm.get() != null) %7B%0A                cm.get().closeExpiredConnections();%0A            %7D else if (thisFuture != null) %7B%0A                thisFuture.cancel(false);%0A            %7D%0A        
 %7D%0A%09%09

Fix memory leak in cleanup task