资讯专栏INFORMATION COLUMN

[case39]聊聊jdk httpclient的executor

dabai / 3066人阅读

摘要:序本文主要研究一下的这里如果的为,则会创建这里如果是的话,参数传递的是如果是同步的方法,则传的值是这里创建了一个,然后调用,这里使用了可以看到这里使用的是的方法注意这个方法是才有的,也是在这里使用的由于默认是使用创建的,

本文主要研究一下jdk httpclient的executor

HttpClientImpl

java.net.http/jdk/internal/net/http/HttpClientImpl.java

    private HttpClientImpl(HttpClientBuilderImpl builder,
                           SingleFacadeFactory facadeFactory) {
        id = CLIENT_IDS.incrementAndGet();
        dbgTag = "HttpClientImpl(" + id +")";
        if (builder.sslContext == null) {
            try {
                sslContext = SSLContext.getDefault();
            } catch (NoSuchAlgorithmException ex) {
                throw new InternalError(ex);
            }
        } else {
            sslContext = builder.sslContext;
        }
        Executor ex = builder.executor;
        if (ex == null) {
            ex = Executors.newCachedThreadPool(new DefaultThreadFactory(id));
            isDefaultExecutor = true;
        } else {
            isDefaultExecutor = false;
        }
        delegatingExecutor = new DelegatingExecutor(this::isSelectorThread, ex);
        facadeRef = new WeakReference<>(facadeFactory.createFacade(this));
        client2 = new Http2ClientImpl(this);
        cookieHandler = builder.cookieHandler;
        connectTimeout = builder.connectTimeout;
        followRedirects = builder.followRedirects == null ?
                Redirect.NEVER : builder.followRedirects;
        this.userProxySelector = Optional.ofNullable(builder.proxy);
        this.proxySelector = userProxySelector
                .orElseGet(HttpClientImpl::getDefaultProxySelector);
        if (debug.on())
            debug.log("proxySelector is %s (user-supplied=%s)",
                      this.proxySelector, userProxySelector.isPresent());
        authenticator = builder.authenticator;
        if (builder.version == null) {
            version = HttpClient.Version.HTTP_2;
        } else {
            version = builder.version;
        }
        if (builder.sslParams == null) {
            sslParams = getDefaultParams(sslContext);
        } else {
            sslParams = builder.sslParams;
        }
        connections = new ConnectionPool(id);
        connections.start();
        timeouts = new TreeSet<>();
        try {
            selmgr = new SelectorManager(this);
        } catch (IOException e) {
            // unlikely
            throw new InternalError(e);
        }
        selmgr.setDaemon(true);
        filters = new FilterFactory();
        initFilters();
        assert facadeRef.get() != null;
    }

这里如果HttpClientBuilderImpl的executor为null,则会创建Executors.newCachedThreadPool(new DefaultThreadFactory(id))

HttpClientImpl.sendAsync

java.net.http/jdk/internal/net/http/HttpClientImpl.java

    @Override
    public  CompletableFuture>
    sendAsync(HttpRequest userRequest, BodyHandler responseHandler)
    {
        return sendAsync(userRequest, responseHandler, null);
    }

    @Override
    public  CompletableFuture>
    sendAsync(HttpRequest userRequest,
              BodyHandler responseHandler,
              PushPromiseHandler pushPromiseHandler) {
        return sendAsync(userRequest, responseHandler, pushPromiseHandler, delegatingExecutor.delegate);
    }

    private  CompletableFuture>
    sendAsync(HttpRequest userRequest,
              BodyHandler responseHandler,
              PushPromiseHandler pushPromiseHandler,
              Executor exchangeExecutor)    {

        Objects.requireNonNull(userRequest);
        Objects.requireNonNull(responseHandler);

        AccessControlContext acc = null;
        if (System.getSecurityManager() != null)
            acc = AccessController.getContext();

        // Clone the, possibly untrusted, HttpRequest
        HttpRequestImpl requestImpl = new HttpRequestImpl(userRequest, proxySelector);
        if (requestImpl.method().equals("CONNECT"))
            throw new IllegalArgumentException("Unsupported method CONNECT");

        long start = DEBUGELAPSED ? System.nanoTime() : 0;
        reference();
        try {
            if (debugelapsed.on())
                debugelapsed.log("ClientImpl (async) send %s", userRequest);

            // When using sendAsync(...) we explicitly pass the
            // executor"s delegate as exchange executor to force
            // asynchronous scheduling of the exchange.
            // When using send(...) we don"t specify any executor
            // and default to using the client"s delegating executor
            // which only spawns asynchronous tasks if it detects
            // that the current thread is the selector manager
            // thread. This will cause everything to execute inline
            // until we need to schedule some event with the selector.
            Executor executor = exchangeExecutor == null
                    ? this.delegatingExecutor : exchangeExecutor;

            MultiExchange mex = new MultiExchange<>(userRequest,
                                                            requestImpl,
                                                            this,
                                                            responseHandler,
                                                            pushPromiseHandler,
                                                            acc);
            CompletableFuture> res =
                    mex.responseAsync(executor).whenComplete((b,t) -> unreference());
            if (DEBUGELAPSED) {
                res = res.whenComplete(
                        (b,t) -> debugCompleted("ClientImpl (async)", start, userRequest));
            }

            // makes sure that any dependent actions happen in the CF default
            // executor. This is only needed for sendAsync(...), when
            // exchangeExecutor is non-null.
            if (exchangeExecutor != null) {
                res = res.whenCompleteAsync((r, t) -> { /* do nothing */}, ASYNC_POOL);
            }
            return res;
        } catch(Throwable t) {
            unreference();
            debugCompleted("ClientImpl (async)", start, userRequest);
            throw t;
        }
    }

这里如果是sendAsync的话,executor参数传递的是delegatingExecutor.delegate;如果是同步的send方法,则executor传的值是null

这里创建了一个MultiExchange,然后调用mex.responseAsync(executor).whenComplete((b,t) -> unreference()),这里使用了executor

MultiExchange.responseAsync

java.net.http/jdk/internal/net/http/MultiExchange.java

    public CompletableFuture> responseAsync(Executor executor) {
        CompletableFuture start = new MinimalFuture<>();
        CompletableFuture> cf = responseAsync0(start);
        start.completeAsync( () -> null, executor); // trigger execution
        return cf;
    }

    private CompletableFuture>
    responseAsync0(CompletableFuture start) {
        return start.thenCompose( v -> responseAsyncImpl())
                    .thenCompose((Response r) -> {
                        Exchange exch = getExchange();
                        return exch.readBodyAsync(responseHandler)
                            .thenApply((T body) -> {
                                this.response =
                                    new HttpResponseImpl<>(r.request(), r, this.response, body, exch);
                                return this.response;
                            });
                    });
    }

可以看到这里使用的是CompletableFuture的completeAsync方法(注意这个方法是java9才有的),executor也是在这里使用的

由于默认是使用Executors.newCachedThreadPool创建的executor,要注意控制并发数及任务执行时间,防止线程数无限制增长过度消耗系统资源

    /**
     * Creates a thread pool that creates new threads as needed, but
     * will reuse previously constructed threads when they are
     * available, and uses the provided
     * ThreadFactory to create new threads when needed.
     *
     * @param threadFactory the factory to use when creating new threads
     * @return the newly created thread pool
     * @throws NullPointerException if threadFactory is null
     */
    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue(),
                                      threadFactory);
    }
RejectedExecutionException

实例代码

    @Test
    public void testAsyncPool(){
        ThreadPoolExecutor executor = ThreadPoolBuilder.fixedPool()
                .setPoolSize(2)
                .setQueueSize(5)
                .setThreadNamePrefix("test-")
                .build();

        List> futureList = IntStream.rangeClosed(1,100)
                .mapToObj(i -> new CompletableFuture())
                .collect(Collectors.toList());
        futureList.stream()
                .forEach(future -> {
                    future.completeAsync(() -> {
                        try {
                            TimeUnit.SECONDS.sleep(3);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                        return "message";
                    },executor);
                });
        CompletableFuture.allOf(futureList
                .toArray(new CompletableFuture[futureList.size()]))
                .join();
    }
这里创建的是fixedPool,指定queueSize为5

日志输出

java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.CompletableFuture$AsyncSupply@76b10754 rejected from java.util.concurrent.ThreadPoolExecutor@2bea5ab4[Running, pool size = 2, active threads = 2, queued tasks = 5, completed tasks = 0]

    at java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2055)
    at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:825)
    at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1355)
    at java.base/java.util.concurrent.CompletableFuture.completeAsync(CompletableFuture.java:2591)
可以看到线程池队列大小起到了限制作用
小结

jdk httpclient的executor在进行异步操作的时候使用,默认创建的是使用Executors.newCachedThreadPool创建的executor,其线程池大小是Integer.MAX_VALUE,因此在使用的时候要注意,最好是改为有界队列,然后再加上线程池的监控。

doc

java.net.http javadoc

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77340.html

相关文章

  • 聊聊jdk httpclientretry参数

    摘要:序本文主要研究一下的参数这里有一个类型的变量,用来记录请求次数另外还有一个,读取的是值,读取不到默认取,为进入该方法的时候,调用,递增请求次数,然后判断有无超出限制,有则返回带有异常的,即通过返回如果没有超出限制,但是执行请求失败,则 序 本文主要研究一下jdk httpclient的retry参数 DEFAULT_MAX_ATTEMPTS java.net.http/jdk/inte...

    ityouknow 评论0 收藏0
  • 聊聊jdk httpclientconnect timeout异常

    摘要:序本文主要研究一下的异常实例代码异常日志如下最后调用这里调用获取连接如果没有连接会新创建一个,走的是这里先是调用了获取连接,然后调用进行连接这里委托给这里如果有设置的话,则会创建一个调用进行连接,如果连接未 序 本文主要研究一下httpclient的connect timeout异常 实例代码 @Test public void testConnectTimeout()...

    张利勇 评论0 收藏0
  • 聊聊jdk httpclientConnectionPool

    摘要:调用计算的时间,这个方法会清理移除并过期的连接除了清理过期的连接外,还通过间接触发,去清理关闭或异常的连接 序 本文主要研究一下jdk httpclient的ConnectionPool HttpConnection HttpConnection.getConnection java.net.http/jdk/internal/net/http/HttpConnection.java ...

    Worktile 评论0 收藏0
  • 浅析 jdk11 中 HttpClient 使用

    摘要:在中也可以直接使用返回的是,然后通过来获取结果阻塞线程,从中获取结果四一点唠叨非常的年轻,网络资料不多,且代码非常精细和复杂,目前来看底层应该是使用了线程池搭配进行异步通讯。 零 前期准备 0 版本 JDK 版本 : OpenJDK 11.0.1 IDE : idea 2018.3 1 HttpClient 简介 java.net.http.HttpClient 是 jdk11 中正式...

    Eminjannn 评论0 收藏0
  • apacheHttpClient默认重试机制

    摘要:异常重试默认重试次,三次都失败则抛出或其他异常 maven org.apache.httpcomponents httpclient 4.5.2 异常重试log 2017-01-31 19:31:39.057 INFO 3873 --- [askScheduler-13] o....

    MartinDai 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<