Keep <b>Proxy</b> Alive, then return or close <b>Client</b><p>
Must Follow a "<code>server.onComplete.accept(proxy)</code>"

@param closed <code>false</code> to return Client to pool and <code>true</code> to close Client
767137
void reset(boolean closed) {
		attributeMap.clear();
		request.reset();
		handler.setBufferSize(MAX_BUFFER_SIZE);
		server.proxyTimeoutQueue.offer(this);
		// "proxy" may close or return "client" before reset
		if (logLevel >= LOG_VERBOSE && client != null) {
			Log.v((closed ? "Client Closed" : "Client Kept Alive") +
					" and Request Unblocked due to Complete Request and Response, " +
					client.toString(false));
		}
		if (!closed && client != null) {
			server.returnClient(client);
		}
		client = null;
		read();
	}
955386
@NotNull
    public Stream<T> onClose(@NotNull final Runnable closeHandler) {
        Objects.requireNonNull(closeHandler);
        final Params newParams = Params.wrapWithCloseHandler(params, closeHandler);
        return new Stream<T>(newParams, iterator);
    }
1302904
private CompletableFuture<CloseResponse> close(CloseRequest request) {
    return getService(request).thenCompose(service -> service.close(request));
  }
1012988
CompletableFuture<Void> close() {
    return closeClient()
        .exceptionally(v -> null)
        .thenCompose(v -> closeServer())
        .exceptionally(v -> null);
  }
1194441
@Override
    public void transportClosed(boolean closedByRemotePeer, boolean mayBlock)
    {
    	parentListener.unregisterClient(this);
        try
        {
            if (localConnection != null)
                localConnection.close();
        }
        catch (Exception e)
        {
            log.error("#"+id+" Could not close local connection",e);
        }
        finally
        {
        	localConnection = null;
        }
    }
1343046
@Override
	public void close() {
		boolean enqueueOnSocketContextClose;
		synchronized(closeLock) {
			if(!closed) {
				closed = true;
				enqueueOnSocketContextClose = true;
			} else {
				enqueueOnSocketContextClose = false;
			}
		}
		List<S> socketsToClose;
		synchronized(sockets) {
			// Gets a copy of the sockets to avoid concurrent modification exception and avoid holding lock
			socketsToClose = new ArrayList<>(sockets.values());
			// Each will be removed from socket.close() below: sockets.clear();
		}
		for(S socket : socketsToClose) {
			try {
				socket.close();
			} catch(Exception exc) {
				logger.log(Level.SEVERE, null, exc);
			}
		}
		if(enqueueOnSocketContextClose) {
			Future<?> future = listenerManager.enqueueEvent(
				new ConcurrentListenerManager.Event<SocketContextListener>() {
					@Override
					public Runnable createCall(final SocketContextListener listener) {
						return new Runnable() {
							@Override
							public void run() {
								listener.onSocketContextClose(AbstractSocketContext.this);
							}
						};
					}
				}
			);
			try {
				future.get();
			} catch(ExecutionException e) {
				logger.log(Level.SEVERE, null, e);
			} catch(InterruptedException e) {
				logger.log(Level.SEVERE, null, e);
				// Restore the interrupted status
				Thread.currentThread().interrupt();
			}
		}
		listenerManager.close();
		synchronized(sockets) {
			if(!sockets.isEmpty()) throw new AssertionError("Not all sockets closed");
		}
	}
426369
ListenableFuture<Void> closeAsync() {
    ListenableFuture<Void> retFuture = null;
    synchronized (lock) {
      if (closureFuture != null) {
        throw new IllegalStateException("Close has already been invoked");
      }
      // Fail all pending waiters.
      Waiter waiter = readWaiters.poll();
      while (waiter != null) {
        waiter.put(newSpannerException(ErrorCode.INTERNAL, "Client has been closed"));
        waiter = readWaiters.poll();
      }
      waiter = readWriteWaiters.poll();
      while (waiter != null) {
        waiter.put(newSpannerException(ErrorCode.INTERNAL, "Client has been closed"));
        waiter = readWriteWaiters.poll();
      }
      closureFuture = SettableFuture.create();
      retFuture = closureFuture;
      pendingClosure =
          totalSessions() + numSessionsBeingCreated + 1 /* For pool maintenance thread */;

      poolMaintainer.close();
      readSessions.clear();
      writePreparedSessions.clear();
      for (final PooledSession session : ImmutableList.copyOf(allSessions)) {
        if (session.leakedException != null) {
          logger.log(Level.WARNING, "Leaked session", session.leakedException);
        }
        if (session.state != SessionState.CLOSING) {
          closeSessionAsync(session);
        }
      }
    }
    retFuture.addListener(
        new Runnable() {
          @Override
          public void run() {
            executorFactory.release(executor);
          }
        },
        MoreExecutors.directExecutor());

    return retFuture;
  }
162336
public void close(Handler<AsyncResult<Void>> completion) {
        if (context == null) {
            context = vertx.getOrCreateContext();
        }

        context.runOnContext(v -> {
            if (http != null) {
                http.close(event -> {
                    logger.info("The server '{}' has been stopped (bound port: {})", name, port);
                    completion.handle(Future.<Void>succeededFuture());
                });
            }
        });
    }
219494
@Handler
    @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
    public void onClose(Close event) throws IOException, InterruptedException {
        boolean subOnly = true;
        for (Channel channel : event.channels()) {
            if (channel instanceof TcpChannelImpl) {
                if (channels.contains(channel)) {
                    ((TcpChannelImpl) channel).close();
                }
            } else {
                subOnly = false;
            }
        }
        if (subOnly || !serverSocketChannel.isOpen()) {
            // Closed already
            fire(new Closed());
            return;
        }
        synchronized (channels) {
            closing = true;
            // Copy to avoid concurrent modification exception
            Set<TcpChannelImpl> conns = new HashSet<>(channels);
            for (TcpChannelImpl conn : conns) {
                conn.close();
            }
            while (!channels.isEmpty()) {
                channels.wait();
            }
        }
        serverSocketChannel.close();
        purger.interrupt();
        closing = false;
        fire(new Closed());
    }
265645
protected boolean tryToClose() {
		ByteBuffer blocker = blockerBuffer.get();
		if (blocker == BUFFER_IS_CLOSED) {
			return true;
		}
		if (blocker != null) {
			return false;
		}
		boolean closed = blockerBuffer.compareAndSet(null, BUFFER_IS_CLOSED);
		if (closed) {
			closeResources();
			return true;
		}
		return false;
	}
1300380
public void preClose() {
    if (explicitClosed.compareAndSet(false, true)) {
      proxy.lock.lock();
      try {
        removeListenerFromSchedulers();

        //closing connections
        closeConnection(waitNewSecondaryProtocol.getAndSet(null));
        closeConnection(waitNewMasterProtocol.getAndSet(null));
        closeConnection(masterProtocol);
        closeConnection(secondaryProtocol);
      } finally {
        proxy.lock.unlock();
      }
    }
  }
541089
public Future<Boolean> send(final String eventPayload)
    {
        if (client == null || client.isClosed()) {
            client = new AsyncHttpClient(clientConfig);
        }

        try {
            final AsyncHttpClient.BoundRequestBuilder requestBuilder = client
                .prepareGet(collectorURI + eventPayload);
            log.debug("Sending event to collector: {}", eventPayload);

            activeRequests.incrementAndGet();
            return client.executeRequest(requestBuilder.build(),
                new AsyncCompletionHandler<Boolean>()
                {
                    @Override
                    public Boolean onCompleted(final Response response)
                    {
                        activeRequests.decrementAndGet();

                        if (response.getStatusCode() == 202) {
                            return true;
                        }
                        else {
                            log.warn("Received response from collector {}: {}", response.getStatusCode(), response.getStatusText());
                            return false;
                        }
                    }

                    @Override
                    public void onThrowable(final Throwable t)
                    {
                        activeRequests.decrementAndGet();
                    }
                });
        }
        catch (IOException e) {
            // Recycle the client
            client.close();
            return null;
        }
    }
220403
public synchronized void close() throws IOException, InterruptedException {
		if (isClosed){
			return;
		}
		
		logger.info("closing client endpoint");
		if (connState == CONN_STATE_CONNECTED) {
			idPriv.disconnect();
			this.wait(1000);
		}
		if (connState >= CONN_STATE_RESOURCES_ALLOCATED) {
			idPriv.destroyQP();
		}
		idPriv.destroyId();
		group.unregisterClientEp(this);
		isClosed = true;
		logger.info("closing client done");
	}
652849
@Override
    public void accept(ClassWriterOutputVisitor visitor) throws IOException {
        proxyBeanDefinitionWriter.accept(visitor);
        try (OutputStream out = visitor.visitClass(proxyFullName)) {
            out.write(classWriter.toByteArray());
            for (ExecutableMethodWriter method : proxiedMethods) {
                method.accept(visitor);
            }
        }
    }
172810
@Override
	public void handleRequest(final Request request) {
		String clientState = request.getParameter(getId());

		if (clientState != null) {
			setCollapsed(clientState.equalsIgnoreCase("closed"));
		}
	}
298565
public synchronized boolean stopServer() {

        if (!isProxyRunning) {
            return false;
        }

        isProxyRunning = false;
        HttpUtil.closeServerSocket(proxySocket);

        try {
            thread.join();   //(PORT_TIME_OUT);
            
        } catch (Exception e) {
        }

        proxySocket = null;

        return true;
    }
11435
@Override
    public void close() {
        if (closed.compareAndSet(false, true)) {
            super.close();
            synchronized (baseClients) {
                for (WebClient wc : baseClients) {
                    wc.close();
                }
            }

            String moduleName = getModuleName();
            synchronized (clientsPerModule) {
                List<JAXRSClientImpl> clients = clientsPerModule.get(moduleName);

                if (clients != null) { // the only way this isn't null is if the same client was closed twice
                    clients.remove(this);
                    if (clients.isEmpty()) {
                        for (String id : busCache.keySet()) {
                            if (id.startsWith(moduleName) || id.startsWith("unknown:")) {
                                busCache.remove(id).shutdown(false);
                            }
                        }
                        clientsPerModule.remove(moduleName);
                    }
                }
            }

            baseClients = null;
        }
    }