package io.vertx.core.net.impl.clientconnection;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.impl.EventLoopContext;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
public class ConnectionManager<K, C> {
private final EndpointProvider<K, C> endpointProvider;
private final Map<K, Endpoint<C>> endpointMap = new ConcurrentHashMap<>();
public ConnectionManager(EndpointProvider<K, C> endpointProvider) {
this.endpointProvider = endpointProvider;
}
public void forEach(Consumer<Endpoint<C>> consumer) {
endpointMap.values().forEach(consumer);
}
public void getConnection(EventLoopContext ctx,
K key,
Handler<AsyncResult<C>> handler) {
Runnable dispose = () -> endpointMap.remove(key);
while (true) {
Endpoint<C> endpoint = endpointMap.computeIfAbsent(key, k -> endpointProvider.create(key, ctx, dispose));
if (endpoint.getConnection(ctx, handler)) {
break;
}
}
}
public void close() {
for (Endpoint<C> conn : endpointMap.values()) {
conn.close();
}
}
}