0

I have a method, I want to run two threads at a time.

The following is the method

@PostMapping(value = "/sendmails")
    public ResponseEntity<Object> sendEmails(@RequestParam("file") MultipartFile reapExcelDataFile) {

        bulkMailProcessor.processor(reapExcelDataFile);

        return ResponseEntity.status(HttpStatus.OK).build();
    }

I want to run bulkMailProcessor.processor(reapExcelDataFile); line and I don't want to wait until the process completed of the mails sending, the main thread need to continue to send mails but another thread need to start and send the result back. How can I achieve this functionality.

2
  • Hi @Jeb - can you please provide some details on what your tech-stack is? Is it Spring? Commented Jul 30, 2020 at 12:14
  • @tveon yes it is spring-boot Commented Jul 30, 2020 at 12:16

2 Answers 2

2

Use CompletableFuture. It will handle creating the thread executor, running the thread, etc.

If you want to just spin off a process and don't care about a return use:

CompletableFuture.runAsync(() -> someConsumingCode; );

If you want to return some value to a function you can pass the result by chaining various methods available from the api...

CompletableFuture.supplyAsync(() -> someSupplyingCode()).thenApply((outputofSomeSupplyingCode) -> consumeOutputOfSomeSupplyingCode(outputOfSomeSupplyingCode));

When you want the main thread to wait for a result you can assign the result to a variable and then call the get method: CompletableFuture.get():

CompletableFuture<String> resultFuture = CompletableFuture.supplyAsync(() -> "HelloWorld");
String result = resultFuture.get();
System.out.println(result); // outputs "HelloWorld"
Sign up to request clarification or add additional context in comments.

Comments

0

Use Executors Framework and keep on submitting task which is your method call. It will internally create new thread for each task and manage all the resources instead of traditional way where you used to create thread and run.

Refer this link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.