Java Code Examples for io.netty.util.concurrent.Promise#tryFailure()

The following examples show how to use io.netty.util.concurrent.Promise#tryFailure() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InflightNameResolver.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static <T> void transferResult(Future<T> src, Promise<T> dst) {
    if (src.isSuccess()) {
        dst.trySuccess(src.getNow());
    } else {
        dst.tryFailure(src.cause());
    }
}
 
Example 2
Source File: SimpleChannelPool.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
     * Tries to retrieve healthy channel from the pool if any or creates a new channel otherwise.尝试从池中检索健康通道(如果有的话)或创建新的通道。
     * @param promise the promise to provide acquire result.
     * @return future for acquiring a channel.
     */
    private Future<Channel> acquireHealthyFromPoolOrNew(final Promise<Channel> promise) {
        try {
//            从deque中获取一个channel,这里是用双端队列存储的channel
            final Channel ch = pollChannel();
            if (ch == null) {
                // No Channel left in the pool bootstrap a new Channel池中没有剩余通道引导新通道
                Bootstrap bs = bootstrap.clone();
                bs.attr(POOL_KEY, this);
//                如果channel不存在就创建一个
                ChannelFuture f = connectChannel(bs);
                if (f.isDone()) {
//                    promise发布连接成功事件
                    notifyConnect(f, promise);
                } else {
                    f.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            notifyConnect(future, promise);
                        }
                    });
                }
                return promise;
            }
            EventLoop loop = ch.eventLoop();
            if (loop.inEventLoop()) {
                doHealthCheck(ch, promise);
            } else {
                loop.execute(new Runnable() {
                    @Override
                    public void run() {
                        doHealthCheck(ch, promise);
                    }
                });
            }
        } catch (Throwable cause) {
            promise.tryFailure(cause);
        }
        return promise;
    }
 
Example 3
Source File: SimpleChannelPool.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private void notifyConnect(ChannelFuture future, Promise<Channel> promise) {
        if (future.isSuccess()) {
            Channel channel = future.channel();
            if (!promise.trySuccess(channel)) {
                // Promise was completed in the meantime (like cancelled), just release the channel again承诺完成的同时(如取消),只是释放渠道再次
//                如果没有连接成功释放channel
                release(channel);
            }
        } else {
            promise.tryFailure(future.cause());
        }
    }
 
Example 4
Source File: PromiseNotificationUtil.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Try to mark the {@link Promise} as failure and log if {@code logger} is not {@code null} in case this fails.尝试将承诺标记为失败,如果日志记录器在失败时不为空,则记录日志。
 */
public static void tryFailure(Promise<?> p, Throwable cause, InternalLogger logger) {
    if (!p.tryFailure(cause) && logger != null) {
        Throwable err = p.cause();
        if (err == null) {
            logger.warn("Failed to mark a promise as failure because it has succeeded already: {}", p, cause);
        } else {
            logger.warn(
                    "Failed to mark a promise as failure because it has failed already: {}, unnotified cause: {}",
                    p, ThrowableUtil.stackTraceToString(err), cause);
        }
    }
}
 
Example 5
Source File: ConnectionFactory.java    From drift with Apache License 2.0 5 votes vote down vote up
private static void notifyConnect(ChannelFuture future, Promise<Channel> promise)
{
    if (future.isSuccess()) {
        Channel channel = future.channel();
        if (!promise.trySuccess(channel)) {
            // Promise was completed in the meantime (likely cancelled), just release the channel again
            channel.close();
        }
    }
    else {
        promise.tryFailure(future.cause());
    }
}
 
Example 6
Source File: ImapClient.java    From NioImapClient with Apache License 2.0 5 votes vote down vote up
private synchronized void send(ImapCommand imapCommand, Promise promise) {
  if (connectionShutdown.get()) {
    promise.tryFailure(new ConnectionClosedException("Cannot write to closed connection."));
    return;
  }

  if ((currentCommandPromise != null && !currentCommandPromise.isDone()) || !isConnected()) {
    PendingCommand pendingCommand = PendingCommand.newInstance(imapCommand, promise);
    pendingWriteQueue.add(pendingCommand);
  } else {
    actuallySend(imapCommand, promise);
  }
}
 
Example 7
Source File: HealthCheckedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Validate that the channel returned by the underlying channel pool is healthy. If so, complete the result future with the
 * channel returned by the underlying pool. If not, close the channel and try to get a different one.
 *
 * @param delegateFuture A completed promise as a result of invoking delegate.acquire().
 * @param resultFuture The future that should be completed with the healthy, acquired channel.
 * @param timeoutFuture The future for the timeout task. This future will be cancelled when a channel is acquired.
 */
private void ensureAcquiredChannelIsHealthy(Promise<Channel> delegateFuture,
                                            Promise<Channel> resultFuture,
                                            ScheduledFuture<?> timeoutFuture) {
    // If our delegate failed to connect, forward down the failure. Don't try again.
    if (!delegateFuture.isSuccess()) {
        timeoutFuture.cancel(false);
        resultFuture.tryFailure(delegateFuture.cause());
        return;
    }

    // If our delegate gave us an unhealthy connection, close it and try to get a new one.
    Channel channel = delegateFuture.getNow();
    if (!isHealthy(channel)) {
        channel.close();
        delegate.release(channel);
        tryAcquire(resultFuture, timeoutFuture);
        return;
    }

    // Cancel the timeout (best effort), and return back the healthy channel.
    timeoutFuture.cancel(false);
    if (!resultFuture.trySuccess(channel)) {
        // If we couldn't give the channel to the result future (because it failed for some other reason),
        // just return it to the pool.
        release(channel);
    }
}
 
Example 8
Source File: DnsNameResolver.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private static void tryFailure(Promise<?> promise, Throwable cause) {
    if (!promise.tryFailure(cause)) {
        logger.warn("Failed to notify failure to a promise: {}", promise, cause);
    }
}
 
Example 9
Source File: SimpleChannelPool.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
private static void closeAndFail(Channel channel, Throwable cause, Promise<?> promise) {
    closeChannel(channel);
    promise.tryFailure(cause);
}
 
Example 10
Source File: HealthCheckedChannelPool.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
/**
 * Time out the provided acquire future, if it hasn't already been completed.
 */
private void timeoutAcquire(Promise<Channel> resultFuture) {
    resultFuture.tryFailure(new TimeoutException("Acquire operation took longer than " + acquireTimeoutMillis +
                                                 " milliseconds."));
}
 
Example 11
Source File: RefreshingAddressResolver.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void doResolve(InetSocketAddress unresolvedAddress, Promise<InetSocketAddress> promise)
        throws Exception {
    requireNonNull(unresolvedAddress, "unresolvedAddress");
    requireNonNull(promise, "promise");
    if (resolverClosed) {
        promise.tryFailure(new IllegalStateException("resolver is closed already."));
        return;
    }
    final String hostname = unresolvedAddress.getHostString();
    final int port = unresolvedAddress.getPort();
    final CompletableFuture<CacheEntry> entryFuture = cache.get(hostname);
    if (entryFuture != null) {
        handleFromCache(entryFuture, promise, port);
        return;
    }

    final CompletableFuture<CacheEntry> result = new CompletableFuture<>();
    final CompletableFuture<CacheEntry> previous = cache.putIfAbsent(hostname, result);
    if (previous != null) {
        handleFromCache(previous, promise, port);
        return;
    }

    final List<DnsQuestion> questions =
            dnsRecordTypes.stream()
                          .map(type -> DnsQuestionWithoutTrailingDot.of(hostname, type))
                          .collect(toImmutableList());
    sendQueries(questions, hostname, result);
    result.handle((entry, unused) -> {
        final Throwable cause = entry.cause();
        if (cause != null) {
            if (entry.hasCacheableCause() && negativeTtl > 0) {
                executor().schedule(() -> cache.remove(hostname), negativeTtl, TimeUnit.SECONDS);
            } else {
                cache.remove(hostname);
            }
            promise.tryFailure(cause);
            return null;
        }

        entry.scheduleRefresh(entry.ttlMillis());
        promise.trySuccess(new InetSocketAddress(entry.address(), port));
        return null;
    });
}