public TCPConnection getConnection(Address dest) throws Exception { TCPConnection conn = null; getLock().lock(); try { conn = conns.get(dest); if (conn != null && conn.isOpen()) return conn; try { conn = new TCPConnection(dest); conn.start(getThreadFactory()); addConnection(dest, conn); if (log.isTraceEnabled()) log.trace("created socket to " + dest); } catch (Exception ex) { if (log.isTraceEnabled()) log.trace("failed creating connection to " + dest); } } finally { getLock().unlock(); } return conn; }
/** * Acceptor thread. Continuously accept new connections. Create a new thread for each new * connection and put it in conns. When the thread should stop, it is interrupted by the thread * creator. */ public void run() { while (!srv_sock.isClosed() && !Thread.currentThread().isInterrupted()) { TCPConnection conn = null; Socket client_sock = null; try { client_sock = srv_sock.accept(); conn = new TCPConnection(client_sock); Address peer_addr = conn.getPeerAddress(); mapper.getLock().lock(); try { boolean currentConnectionOpen = mapper.hasOpenConnection(peer_addr); boolean replaceWithNewConnection = false; if (currentConnectionOpen) { replaceWithNewConnection = peer_addr.compareTo(local_addr) > 0; } if (!currentConnectionOpen || replaceWithNewConnection) { mapper.removeConnection(peer_addr); mapper.addConnection(peer_addr, conn); conn.start(mapper.getThreadFactory()); // starts handler thread on this socket } else { Util.close(conn); } } finally { mapper.getLock().unlock(); } } catch (SocketException se) { boolean threadExiting = srv_sock.isClosed() || Thread.currentThread().isInterrupted(); if (threadExiting) { break; } else { if (log.isWarnEnabled()) log.warn("Could not accept connection from peer ", se); Util.close(conn); Util.close(client_sock); } } catch (Exception ex) { if (log.isWarnEnabled()) log.warn("Could not read accept connection from peer " + ex); Util.close(conn); Util.close(client_sock); } } if (log.isTraceEnabled()) log.trace(Thread.currentThread().getName() + " terminated"); }