Channel[] channelToClose = channels.values().toArray(new Channel[channels.values().size()]);
if (channelToClose.length > 0) {
final AtomicInteger latch = new AtomicInteger(channelToClose.length);
for (Channel channel : channelToClose) {
log.debug("Closing channel {}", channel.getId());
channel.close(immediately).addListener(new SshFutureListener() {
public void operationComplete(SshFuture sshFuture) {
if (latch.decrementAndGet() == 0) {
log.debug("Closing IoSession");
ioSession.close(true).addListener(new IoSessionCloser());
}