简体   繁体   中英

completableFuture task should execute independently with main method task

If i call future.get() for every completableFuture task, then only my functionality works fine to write multiple files simultaneously. But if i remove future.get() code then it is not working fine to write multiple files.For that i should add future.get() code.

FYI i am calling below method from main method but what happens here is that until all tasks being completed by calling method, my main method thread also wait to complete and stop to execute other code of main method. But my purpose is that it should call other code in main thread and calling method should work asynchronously. It should not impact my main method code. So can you help me to implement as per my requirement.

Below is code for the same:-

  private static void createCompletableFuture(ByteArrayOutputStream baOS, int totalBytes, 
            List<FileUploadMultiLocator> fileUploadList) {
        ExecutorService threadPool = Executors.newFixedThreadPool(4);
        for (FileUploadMultiLocator fileUploadMultiLocator : fileUploadList) {
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() ->{
                System.out.println(Thread.currentThread().getName() + " secondary task is called");
                fileUploadMultiLocator.baOS.write(baOS.toByteArray(), 0, totalBytes);
                fileUploadMultiLocator.setTotalBytes(totalBytes);
                threadPool.execute(fileUploadMultiLocator);
                 return 20;
            },threadPool);
            try {
                 future.get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        threadPool.shutdown();
        try {
            threadPool.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         return;
    }

you made asynchronous calls in your createCompletableFuture method, but I guess you are calling this method from main thread that's why your main thread waits to createCompletableFuture return. Call this method from main method using another thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM