Submit every connection to a fixed pool
Submit every connection to a fixed pool
Answer
ExecutorService pool = Executors.newFixedThreadPool(50); try (ServerSocket listener = new ServerSocket(1313)) { while (true) { pool.submit(new DaytimeHandler(listener.accept())); } } finally { pool.shutdown(); }
One line replaces `new Thread(...).start()`, and with it the unbounded-thread bug: the fiftieth connection gets a thread, the fifty-first waits in the executor queue. The `finally` guarantees `shutdown()`, without which the non-daemon pool threads keep the JVM alive forever.
Harold 4e ch9 §Multithreaded Servers; ch3 §Thread Pools and Executors