Future.get() 在配置RejectedExecutionHandler为ThreadPoolExecutor.DiscardPolicy策略时一直阻塞

本文探讨了Java线程池中使用特定拒绝策略时出现的阻塞问题,并提供了三种解决方案,包括修改拒绝策略、使用带超时的获取方法等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自:https://blog.csdn.net/doctor_who2004/article/details/115647638

1、先复现这种情况:

package com.sdcuike.java11;

import java.util.concurrent.*;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

public class Demo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("rpc-pool-%d").setDaemon(true).build();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.HOURS, new SynchronousQueue<>(), threadFactory, new ThreadPoolExecutor.DiscardPolicy() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                System.out.println("rejectedExecution");
     
                super.rejectedExecution(r, executor);
            }
        });
     
        threadPoolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.HOURS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
     
        Future<String> future = threadPoolExecutor.submit(new Callable<String>() {
     
            @Override
            public String call() throws Exception {
                return "done";
            }
        });
     
        String result = future.get();
        System.out.println(result);
        System.out.println("done....");
    }

}

线程池中线程的配置为daemon线程(后台运行),当我们的main线程退出时,后台线程也会退出。会输出

done… 而现实的结果是main线程一直阻塞在future.get()调用:

img

2、why?

我们看下源码:java.util.concurrent.FutureTask#get()

public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

FutureTask 内部有几种状态:

private static final int NEW          = 0;
    private static final int COMPLETING   = 1;
    private static final int NORMAL       = 2;
    private static final int EXCEPTIONAL  = 3;
    private static final int CANCELLED    = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED  = 6;

当状态state<=COMPLETING 即COMPLETING和NEW两种状态时,会一直阻塞:awaitDone(false, 0L)。

FutureTask的状态设置是在线程池ThreadPoolExecutor执行过程中所设置的,一般情况下线程池队列不满,即不会执行RejectedExecutionHandler处理不能处理的任务时,状态都会设置为state > COMPLETING的某个状态 ,但线程池执行RejectedExecutionHandler的时候,java内置的拒绝策略有:

CallerRunsPolicy
public static class CallerRunsPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() { }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

这种策略会使用调用线程池执行任务的当前线程执行,java.util.concurrent.FutureTask#run() 执行肯定会设置新的完成状态。

AbortPolicy
public static class AbortPolicy implements RejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }

这种策略是线程池没配置的情况下使用的 默认策略,直接抛出异常,线程池根本就不会执行任务。

DiscardOldestPolicy
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public DiscardOldestPolicy() { }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }

丢弃任务队列队头的任务,任何重试执行提交的新任务。状态肯定会设置。

DiscardPolicy
public static class DiscardPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public DiscardPolicy() { }

        /**
         * Does nothing, which has the effect of discarding task r.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }

这种策略什么都不做,任务的状态自然是初始状态,永远不会更新任务的状态,导致java.util.concurrent.FutureTask#get() 一直阻塞。

所以,最好的情况下是不使用这种策略,或者使用java.util.concurrent.FutureTask#get(long, java.util.concurrent.TimeUnit) 带有超时的方法获取结果,或者重写策略,取消任务: ((FutureTask) r).cancel(true);

 @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                System.out.println("rejectedExecution");
                ((FutureTask) r).cancel(true)
                super.rejectedExecution(r, executor);
            }

3、解决一直阻塞的问题总结

1、重写DiscardPolicy,取消任务: ((FutureTask) r).cancel(true)。
2、不使用DiscardPolicy,建议还是用线程池默认的AbortPolicy,可以重写,打印日志,再调用super.rejectedExecution(r, executor),抛出默认异常行为。
3、使用java.util.concurrent.FutureTask#get(long, java.util.concurrent.TimeUnit) 带有超时的方法获取结果

### Spring Boot 中 ThreadPoolExecutor 的实现与配置 在 Spring Boot 应用中,`ThreadPoolExecutor` 是一种常用的线程池管理工具,用于高效地管理和调度任务。通过合理配置 `ThreadPoolExecutor`,可以显著提升应用性能并优化资源利用。 #### 配置自定义线程池 Bean 为了在 Spring Boot 中使用 `ThreadPoolExecutor`,可以通过创建一个自定义的线程池 Bean 来实现。以下是具体方法: 1. **引入依赖** 如果尚未引入必要的依赖库,则需确保项目的 `pom.xml` 文件中有以下内容: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` 2. **定义线程池 Bean** 创建一个配置类来声明线程池 Bean,并设置其核心参数。这些参数包括但不限于核心线程数、最大线程数、队列容量以及拒绝策略等[^3]。 下面是一个典型的线程池配置示例: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; @Configuration public class ThreadPoolConfig { @Bean(name = "customTaskExecutor") public ThreadPoolExecutor taskExecutor() { int corePoolSize = 5; // 核心线程数量 int maxPoolSize = 10; // 最大线程数量 long keepAliveTime = 60L; // 线程存活间(秒) int queueCapacity = 100; // 队列容量 RejectedExecutionHandler handler = new AbortPolicy(); // 设置拒绝策略 return new ThreadPoolExecutor( corePoolSize, maxPoolSize, keepAliveTime, java.util.concurrent.TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueCapacity), new ThreadPoolExecutor.CallerRunsPolicy() ); } } ``` 3. **注入并使用线程池** 定义完成后,在服务层或其他组件中可通过自动装配的方式获取该线程池实例,并提交异步任务给它处理。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.concurrent.Future; @Service public class TaskService { private final ThreadPoolExecutor executor; @Autowired public TaskService(ThreadPoolExecutor executor) { this.executor = executor; } public void executeTask(Runnable task) { executor.execute(task); } public Future<?> submitTask(Callable<?> callable) { return executor.submit(callable); } } ``` 4. **调整拒绝策略** 当线程池中的任务过多而无法及处理,可以选择不同的拒绝策略以应对这种情况。常见的拒绝策略有四种:AbortPolicy、CallerRunsPolicy、DiscardOldestPolicy 和 DiscardPolicy。可以根据实际需求灵活选用合适的策略。 #### 性能调优建议 - 合理设定线程池的核心大小和最大大小,避免因线程过载而导致系统崩溃。 - 对于高并发场景下可能存在的大量短生命周期任务,应适当增加队列长度或采用更高效的阻塞队列结构。 - 使用监控工具跟踪线程池运行状态,以便动态调整相关参数。 ```java // 示例代码片段展示如何捕获异常情况下的日志记录逻辑 try { future.get(); } catch (Exception e) { log.error("Error occurred while processing the task", e); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值