Reputation: 517
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.
Upvotes: 0
Views: 191
Reputation: 2874
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"
Upvotes: 2
Reputation: 229
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.
Upvotes: 0