nbNonNulls++;
}
}
if (nbNonNulls == 0) {
return new Closeable() {
final CloseFuture future = new DefaultCloseFuture(lock);
public boolean isClosed() {
return future.isClosed();
}
public boolean isClosing() {
return isClosed();
}
public CloseFuture close(boolean immediately) {
future.setClosed();
return future;
}
};
} else if (nbNonNulls == 1) {
for (Closeable closeable : closeables) {
if (closeable != null) {
return closeable;
}
}
throw new IllegalStateException();
} else {
return new Closeable() {
final DefaultCloseFuture future = new DefaultCloseFuture(lock);
final AtomicBoolean closing = new AtomicBoolean();
public boolean isClosed() {
return future.isClosed();
}
public boolean isClosing() {
return closing.get();
}
public CloseFuture close(final boolean immediately) {
if (closing.compareAndSet(false, true)) {
final Iterator<Closeable> iterator = Arrays.asList(closeables).iterator();
SshFutureListener<CloseFuture> listener = new SshFutureListener<CloseFuture>() {
public void operationComplete(CloseFuture previousFuture) {
while (iterator.hasNext()) {
Closeable c = iterator.next();
if (c != null) {
CloseFuture nextFuture = c.close(immediately);
nextFuture.addListener(this);
return;
}
}
if (!iterator.hasNext()) {
future.setClosed();
}
}
};
listener.operationComplete(null);
}