并发场景多个线程统一全局超时时间

业务场景

我需要请求算法那边同时获取多个业务场景(10多种,嗯。。算法没提供多业务一次性全部返回的模型)的的数据每个业务场景的数据都不相同但是由于是主链路的接口不想等待太长时间想共用500毫秒(可动态配置) 超过时间直接舍弃掉,此时想到的解决方案。

方法1自定义超时时间

List<CompletableFuture<Integer>> list = new ArrayList<>();
        //最大等待时间
        long maxTime = 500L;
        //开始时间
        long startTime = System.currentTimeMillis();
        List<Integer> result = new ArrayList<>();
        for (CompletableFuture<Integer> integerCompletableFuture : list) {
    
    
            Integer integer = null;
            try {
    
    
                long outTime = maxTime - (System.currentTimeMillis() - startTime);
                //兜底
                if (outTime <= 0) {
    
    
                    integer = integerCompletableFuture.get(100L, TimeUnit.MILLISECONDS);
                }
                integer = integerCompletableFuture.get(outTime, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
            if (Objects.nonNull(integer)) {
    
    
                result.add(integer);
            }
        }
        // 使用 result


坏处第一个线程时间过长就会挤压后续线程的等待时间,做了个兜底

方法2使用CountDownLatch

 public static void main(String[] args) {
    
    
        List<Integer> list = new CopyOnWriteArrayList<>();
        try {
    
    
            CountDownLatch countDownLatch = new CountDownLatch(10);
            for (int i = 0; i < 10; i++) {
    
    
                CompletableFuture.runAsync(() -> {
    
    
                    int max = 200;
                    int min = 50;
                    Random random = new Random();

                    int s = random.nextInt(max) % (max - min + 1) + min;
                    try {
    
    
                        Thread.sleep(s);
                        //业务返回值
                        if (true) {
    
    
                            //拿到业务值,这里只是模拟使用 由于并发修改全局需要加锁
                            //此处使用了CopyOnWriteArrayList 无需加锁 
                            //但是源码如ConcurrentHashMap全局使用写的都进行了加锁
                            list.add(s);
                            //如果成功返回 -1
                            countDownLatch.countDown();
                        }
                    } catch (Exception e) {
    
    
                        e.printStackTrace();
                    }
                });
            }
            //如果countDownLatch 为0 继续执行 就不用等1500ms
            countDownLatch.await(1500, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println(list);
    }

推荐
输出

[71, 80, 91, 107]

第三种使用CompletableFutureAPI

我自己整理的使用链接
注意 await和get 并不会中断任务执行

但是存在问题就是 虽然 await和get 都会在规定时间过后继续执行/抛出异常,具体处理方案如下(混合)

await()

public class Test3 {
    
    

    public static void main(String[] args) {
    
    
        List<String> list = new CopyOnWriteArrayList<>();
        CountDownLatch downLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
    
    
            int finalI = i;
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
    
    
                if (finalI == 8) {
    
    //模拟某个业务阻塞
                    try {
    
    
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }
                // String str = get(); 模拟业务逻辑
                list.add(String.valueOf(finalI));
                downLatch.countDown();
            });
        }

        /**
         *  downLatch.await 只是表示不再等待 线程的任务还是会继续执行
         */
        try {
    
    
            downLatch.await(1000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        System.out.println("任务使用前 size : " + list.size());

        //模拟主任务执行时间
        try {
    
    
            Thread.sleep(1500);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("任务使用后 size: " + list.size());

    }

}

结果

任务使用前 size : 9
任务使用后 size: 10

get()

public class Test4 {
    
    
    
    public static void main(String[] args) {
    
    
        Map<String, String> map = new Hashtable<>();
        List<CompletableFuture<Void>> list1 = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
    
    
            int finalI = i;
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
    
    
                if (finalI == 8) {
    
    
                    try {
    
    
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }
                // String str = get(); 存储返回数据
                map.put(String.valueOf(finalI), String.valueOf(finalI));

            });
            //存储future
            list1.add(voidCompletableFuture);
        }
        /**
         *  get同理 只是表示不再等待并抛出来异常 线程的任务还是会继续执行
         */
        CompletableFuture[] completableFutures = new CompletableFuture[6];
        CompletableFuture[] futures = list1.toArray(completableFutures);
        try {
    
    
            CompletableFuture.allOf(futures).get(1000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
    
    
            //异常自己处理掉 业务可以不抛出
            e.printStackTrace();
        }

//        /**
//         * 如果就想 超过时间不再使用的数据 就将完成数据放置到另一个map当中
//         * java.util.concurrent.TimeoutException
//         * 	at java.util.concurrent.CompletableFuture.timedGet(CompletableFuture.java:1771)
//         * 	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1915)
//         * 	at com.example.demolog.controller.Test2.main(Test2.java:44)
//         *
//         *  size: 10
//         * map2 size: 9
//         */
//        Map<String, String> map2 = new Hashtable<>(map);
        System.out.println("多线程返回值使用前 size: " + map.size());

        try {
    
    
            Thread.sleep(1500);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("多线程返回值使用后 size: " + map.size());
//        System.out.println("map2 size: " + map2.size());
    }


}

结果
异常可以自己捕获掉

java.util.concurrent.TimeoutException
	at java.util.concurrent.CompletableFuture.timedGet(CompletableFuture.java:1771)
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1915)
	at com.example.demolog.controller.Test4.main(Test4.java:42)
多线程返回值使用前 size: 9
多线程返回值使用后 size: 10

只用超时前的数据

可以直接将数据直接放到另一个map存储起来

猜你喜欢

转载自blog.csdn.net/qq_42261668/article/details/121446819