@Override public CompletableFuture<Connection> connect(InetSocketAddress address) { Context context = getContext(); LocalServer server = registry.get(address); if (server == null) { return Futures.exceptionalFutureAsync( new TransportException("failed to connect"), context.executor()); } LocalConnection connection = new LocalConnection(id, this.context, connections); connections.add(connection); return server.connect(connection).thenApplyAsync(v -> connection, context.executor()); }
@Override public CompletableFuture<Void> close() { CompletableFuture<Void> future = new CompletableFuture<>(); Context context = getContext(); CompletableFuture[] futures = new CompletableFuture[connections.size()]; int i = 0; for (LocalConnection connection : connections) { futures[i++] = connection.close(); } CompletableFuture.allOf(futures).thenRunAsync(() -> future.complete(null), context.executor()); return future; }
/** Returns the current execution context. */ private Context getContext() { Context context = Context.currentContext(); if (context == null) { throw new IllegalStateException("not on a Copycat thread"); } return context; }