diff --git a/server/src/main/java/org/elasticsearch/transport/TcpTransport.java b/server/src/main/java/org/elasticsearch/transport/TcpTransport.java index b6232c5df47b3..8e7776b9d615c 100644 --- a/server/src/main/java/org/elasticsearch/transport/TcpTransport.java +++ b/server/src/main/java/org/elasticsearch/transport/TcpTransport.java @@ -388,7 +388,7 @@ private InetSocketAddress bindToPort(final String name, final InetAddress hostAd PortsRange portsRange = new PortsRange(port); final AtomicReference lastException = new AtomicReference<>(); final AtomicReference boundSocket = new AtomicReference<>(); - closeLock.readLock().lock(); + closeLock.writeLock().lock(); try { if (lifecycle.initialized() == false && lifecycle.started() == false) { throw new IllegalStateException("transport has been stopped"); @@ -396,15 +396,8 @@ private InetSocketAddress bindToPort(final String name, final InetAddress hostAd boolean success = portsRange.iterate(portNumber -> { try { TcpServerChannel channel = bind(name, new InetSocketAddress(hostAddress, portNumber)); - synchronized (serverChannels) { - List list = serverChannels.get(name); - if (list == null) { - list = new ArrayList<>(); - serverChannels.put(name, list); - } - list.add(channel); - boundSocket.set(channel.getLocalAddress()); - } + serverChannels.computeIfAbsent(name, k -> new ArrayList<>()).add(channel); + boundSocket.set(channel.getLocalAddress()); } catch (Exception e) { lastException.set(e); return false; @@ -415,7 +408,7 @@ private InetSocketAddress bindToPort(final String name, final InetAddress hostAd throw new BindTransportException("Failed to bind to [" + port + "]", lastException.get()); } } finally { - closeLock.readLock().unlock(); + closeLock.writeLock().unlock(); } if (logger.isDebugEnabled()) { logger.debug("Bound profile [{}] to address {{}}", name, NetworkAddress.format(boundSocket.get()));