@Override
    public void close(@Nullable final StreamError error, final boolean networkInterruption) {
        if (state.compareAndSet(State.OPEN, State.CLOSED)) {
            Log.trace("Closing {} with optional error: {}", this, error);

            ChannelFuture f;

            if (session != null) {

                if (!networkInterruption) {
                    // A 'clean' closure should never be resumed (OF-2752).
                    session.getStreamManager().formalClose();
                }

                // Ensure that the state of this connection, its session and the Netty Channel are eventually closed.
                session.setStatus(Session.Status.CLOSED);

                // Only send errors or stream closures if the open <stream:stream> occurred, inferred by having a session.
                // TODO: Are there edge cases here?
                String rawEndStream = "";
                if (error != null) {
                    rawEndStream = error.toXML();
                }
                rawEndStream += "</stream:stream>";

                f = channelHandlerContext.writeAndFlush(rawEndStream);
            } else {
                f = channelHandlerContext.newSucceededFuture();
            }

            f.addListener(e -> Log.trace("Flushed any final bytes, closing connection."))
                .addListener(ChannelFutureListener.CLOSE)
                .addListener(e -> {
                    Log.trace("Notifying close listeners.");
                    notifyCloseListeners()
                        .whenComplete((v,t) -> {
                            closeListeners.clear();
                            if (t != null) {
                                Log.warn("Exception while invoking close listeners for {}", this, t);
                            }
                        });
                })
                .addListener(e -> Log.trace("Finished closing connection."));
        }
    }
Flag that specifies if the connection should be considered closed. Closing a NIO connection
is an asynchronous operation so instead of waiting for the connection to be actually closed just
keep this flag to avoid using the connection between #close was used and the socket is actually
closed.
xmppserver/src/main/java/org/jivesoftware/openfire/nio/NettyConnection.java