NetworkStreamManager: introduce ExecutorService to manage stream thread lifecycle...
authorTJ <hacker@iam.tj>
Wed, 10 Jun 2015 06:58:30 +0000 (07:58 +0100)
committerTJ <hacker@iam.tj>
Wed, 10 Jun 2015 06:58:30 +0000 (07:58 +0100)
src/uk/ac/ntu/n0521366/wsyd/libs/net/NetworkStreamManager.java

index c5640a1..7a4797b 100644 (file)
@@ -26,6 +26,9 @@ package uk.ac.ntu.n0521366.wsyd.libs.net;
 import java.util.Enumeration;
 import java.util.Random;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Manages active TCP connections.
@@ -59,12 +62,18 @@ public class NetworkStreamManager implements NetworkSocketClosing {
      */
     public ConcurrentHashMap<Long, NetworkStream> _tcpStreams;
     
+    /**
+     * Thread manager
+     */
+    private final ExecutorService _pool;
+
     /**
      * Default constructor.
      */
     public NetworkStreamManager() {
         random = new Random();
         _tcpStreams = new ConcurrentHashMap<>();
+        _pool = Executors.newCachedThreadPool();
     }
     
     /**
@@ -87,14 +96,14 @@ public class NetworkStreamManager implements NetworkSocketClosing {
                     _tcpStreams.put(tempKey, netStream);
                     result = tempKey;
                     netStream._key = tempKey;
-                    netStream.execute();
+                    _pool.execute(netStream);
                 }
                 else {
                     if ((userID < 0 && userID > TEMPCLIENT) || userID > 0) {
                         _tcpStreams.put(userID, netStream);
                         result = userID;
                         netStream._key = userID;
-                        netStream.execute();
+                        _pool.execute(netStream);
                     }
                 }
             }
@@ -142,6 +151,17 @@ public class NetworkStreamManager implements NetworkSocketClosing {
             _tcpStreams.get(key).close(); // close the network stream
             _tcpStreams.remove(key);
         }
+        _pool.shutdown();
+        try {
+            result = _pool.awaitTermination(30, TimeUnit.SECONDS);
+            if (!result) {
+                _pool.shutdownNow();
+                result = _pool.awaitTermination(30, TimeUnit.SECONDS);
+            }
+        } catch (InterruptedException ex) {
+            _pool.shutdownNow();
+            Thread.currentThread().interrupt();
+        }
         return result;
     }