并行查询的超时时间设置

众所周知,并行查询可以提高程序运行效率。主线程需要等待所有子线程把数据查询出结果,如果没有设置超时时间,就需要主线程就会一直阻塞到那里,从而占用服务器资源,那么如何设置超时时间呢?

1.在SpringBoot项目中引入线程池

java 复制代码
@EnableAsync
@Configuration
public class ThreadPoolsConfig {

    @Value("${AsyncTaskExecutor.corePooleSize:6}")
    private Integer corePooleSize;
    @Value("${AsyncTaskExecutor.maxPoolSize:15}")
    private Integer maxPoolSize;
    @Value("${AsyncTaskExecutor.queueCapacity:20000}")
    private Integer queueCapacity;

    /**
     * 自定义线程池
     */
    @Bean("myTaskExecutor")
    public AsyncTaskExecutor getMyTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("TaskThreadExec--");
        executor.setCorePoolSize(corePooleSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        // 放弃等待队列中最旧的任务来添加新的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
        return executor;
    }

}

2.使用java.util.concurrent.CompletableFuture进行并行查询(未设置超时时间)

java 复制代码
        CompletableFuture[] asyncList = new CompletableFuture[]{
                CompletableFuture.runAsync(() -> queryDataA(), asyncTaskExecutor),
                CompletableFuture.runAsync(() -> queryDataB(), asyncTaskExecutor)
        };
        CompletableFuture.allOf(asyncList).join();

3.使用java.util.concurrent.CompletableFuture进行并行查询(设置超时时间)

java 复制代码
        CompletableFuture[] asyncList = new CompletableFuture[]{
                CompletableFuture.runAsync(() -> queryDataA(), asyncTaskExecutor),
                CompletableFuture.runAsync(() -> queryDataB(), asyncTaskExecutor)
        };

        try {
         	CompletableFuture.allOf(asyncList).get(3, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            System.err.println("多线程查询"+e.getMessage());
            Thread.currentThread().interrupt();
        }

需要说明的是,这里的interrupt方法也可以不调用。

interrupt方法的作用如下:

线程A在执行sleep,wait,join时,线程B调用线程A的interrupt方法,的确这一个时候A会有InterruptedException 异常抛出来。

但这其实是在sleep、wait、join这些方法内部会不断检查中断状态的值,而自己抛出的InterruptedException

java 复制代码
import java.util.Date;

public class MyThread extends Thread{

    @Override
    public void run() {
        while (!isInterrupted()){
            System.out.println(new Date());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        myThread.start();

        //1秒后打断子线程
        Thread.sleep(1000);
        myThread.interrupt();
    }
}
相关推荐
lemon_sjdk5 分钟前
JavaScript 常用关键字全解析
开发语言·javascript·ecmascript
linx2958 分钟前
单元五 · 对称认知·下:编译与链接
linux·c语言·开发语言·c++·嵌入式硬件
2501_9304724425 分钟前
从物理机到 CVM 全流程落地:部署脚本的 8 个云化改造点(附代码对比)
开发语言·人工智能·架构·腾讯云·perl
lhldsg29 分钟前
多商户团购系统源码:技术架构选型与二次开发实战指南
java·小程序·架构
亦暖筑序30 分钟前
AgentScope Java 实战:@Tool 方法里到底该不该写业务逻辑?
java·agent·ai编程
脉动数据行情134 分钟前
Java SpringBoot 国际期货批量采集实践 美原油 / 黄金 / 指数期货定时落库
java·开发语言·spring boot
C++ 老炮儿的技术栈37 分钟前
西门子 S7 常用存储区(I/Q/M/T/C/DB/PI/PQ)
linux·开发语言·c++·windows·qt·io
Zane199442 分钟前
写Stream时踩过的坑:中间操作不会真正执行,直到你调用这一个方法
java·后端
EXI-小洲1 小时前
Spring AI (第二章)大模型对话上下文记忆
java·人工智能·spring
码行山野赴时序归途1 小时前
顺序表(Sequential List)详解:从数组到 C 语言实现
c语言·开发语言·数据结构·算法