Java code concurrency operation consultation

demand

when querying the list of data in paging, I want to query the total number of items at the same time, but I think the following code is a little tedious, is there any easier way, or is there any third-party framework that can simplify logic like this

    ExecutorService executorService = Executors.newFixedThreadPool(2);
    CountDownLatch countDownLatch = new CountDownLatch(2);
    Map<String, Object> map = new HashMap<>();
    // 
    executorService.submit(() -> {
        List<Integer> data = Lists.newArrayList(1, 2, 3);
        map.put("data", data);
        countDownLatch.countDown();
    });
    // 
    executorService.submit(() -> {
        int count = 10;
        map.put("count", count);
        countDownLatch.countDown();
    });

    countDownLatch.await();
    
    System.out.println(map);
Mar.07,2021

HashMap is not thread safe, so you will have a problem using it this way. It is not clear what you are trying to achieve, at least from the above example, multithreading is not only unnecessary, but also introduces new problems. Talk about your specific application scenario, maybe your idea is appropriate in a particular scenario.


A simple scheme

        CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            List<Integer> data = Lists.newArrayList(1, 2, 3);
            return data;
        }).thenAcceptBoth(CompletableFuture.supplyAsync(() -> 10), (d, c) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("data", d);
            map.put("count", c);
            System.out.println(map);
        });
        future.get();
Menu