~/ learn/ comp-348/ cards/ Thread-pooled servers
1 of 5

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

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/37389107-0de0-422f-b4fb-fc81a884f35b/flashcard utf-8 LF