public void close() { Thread t = null; // This code avoids deadlock of calling close() from different threads // and avoid multiple closes synchronized (access) { if (worker != null) { t = worker; worker = null; } } // Then, releasing the lock, we perform closing, only once: if (t != null) { requestStop = true; t.interrupt(); // While the worker closes, we can free up the queue: EOFException eof = new EOFException(); // synchronized (resultQueue) { for (CommandResult dr : resultQueue.values()) { dr.sendFailure(eof); } resultQueue.clear(); // } // try { // t.join(); // } catch (InterruptedException ignored) { // } connector.close(); } }