package com.box.boxjavalibv2;

import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import org.apache.http.conn.ClientConnectionManager;

public class ConnectionMonitor {

    /**
     * 
     * @param connManager
     * @param timePeriodCleanUpIdleConnection
     *            clean up idle connection every such period of time.
     * @param idleTimeThreshold
     *            time threshold, an idle connection will be closed if idled above this threshold of time.
     */
    public static void monitorConnection(final ClientConnectionManager connManager, final long timePeriodCleanUpIdleConnection, final long idleTimeThreshold) {
        final WeakReference<ClientConnectionManager> ref = new WeakReference<ClientConnectionManager>(connManager);
        Thread monitorThread = new Thread() {

            @Override
            public void run() {
                try {
                    ClientConnectionManager connMan = ref.get();
                    // while not garbage collected.
                    while (connMan != null) {
                        synchronized (this) {
                            wait(timePeriodCleanUpIdleConnection);
                            // Close expired connections
                            connMan.closeExpiredConnections();
                            connMan.closeIdleConnections(idleTimeThreshold, TimeUnit.SECONDS);
                        }
                    }
                }
                catch (InterruptedException ex) {
                    // terminate
                }
            }
        };
        monitorThread.start();
    }
}

@@ -533,22 +533,16 @@
 nection(
-final 
 ClientCo
@@ -642,24 +642,24 @@
 hreshold) %7B%0A
+
         fina
@@ -762,16 +762,44 @@
 nager);%0A
+        connManager = null;%0A
         
@@ -913,16 +913,105 @@
   try %7B%0A
+                    while (true) %7B%0A                        synchronized (this) %7B%0A        
         
@@ -1091,85 +1091,78 @@
     
-// while not garbage collected.%0A                    while (connMan != null) %7B
+        if (connMan == null) %7B%0A                                return;
 %0A   
@@ -1182,37 +1182,22 @@
         
-synchronized (this) %7B
+    %7D%0A
 %0A       

fix bug that monitor thread cannot be terminated