SocketListener extends Thread { @Override public final void run() { try { while (!isInterrupted()) { Socket s = server.accept(); logger.info("New connection from: {}", s); executor.execute(tasks.getTask(s)); } } catch (IOException e) { logger.error("IOException while accepting connection: {}", e.getMessage()); } finally { logger.info("entered finally block. interrupt status is: {}", isInterrupted()); executor.shutdownNow(); } } SocketListener(
            ServerSocket server,
            final ExecutorService executor,
            final SocketTaskFactory taskFactory);  SocketListener(
            final int bindingPort,
            final ServerSocketFactory serverSocketFactory,
            final ExecutorService executor,
            final SocketTaskFactory taskFactory); @Override final void run(); @Override final void interrupt();  }
@Test public void testRun() throws IOException, InterruptedException { ServerSocket dummy = new ServerSocket(0); int listenerPort = dummy.getLocalPort(); dummy.close(); SocketTaskFactory tf = mock(SocketTaskFactory.class); Runnable task = mock(Runnable.class); when(tf.getTask(isA(Socket.class))).thenReturn(task); SocketListener lt = new SocketListener(listenerPort, ServerSocketFactory.getDefault(), Executors.newCachedThreadPool(), tf); lt.start(); Socket s = new Socket(); s.connect(new InetSocketAddress(listenerPort)); Thread.sleep(200); lt.interrupt(); lt.join(); verify(task).run(); }