Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to execute simple async task in Java?

I want to asynchronously invoke a function which does something separately from main thread. I'm new in Java concurrency, so i ask what is the best way to perform action like this:

for(File myFile : files){
    MyFileService.resize(myfile)  <--- this should be async
}

The while loop goes on while function MyFileService.resize works in background with each of my files in collection.

I heard that CompletionStage from Java8 could be good way to do it. What is the best way?

like image 991
Konrad Dziurdź Avatar asked Dec 09 '16 09:12

Konrad Dziurdź


People also ask

How do you create async method in Java?

Async<Integer, Long> asyncFunction = new Async<Integer, Long>(input -> factorial(input)); Future<Long> asyncFuture = asyncFunction. apply(number); long result = asyncFuture. get(); Here the apply method executes the operation using the ExecutorService.

Does Java support asynchronous programming?

Java concurrency is the functionality that enables asynchronous programming in Java. Concurrency is mainly the ability to run several programs or applications parallelly smoothly.

How do I create async tasks?

You can use await Task. Yield(); in an asynchronous method to force the method to complete asynchronously. Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.


3 Answers

How about Future in Java8, example:

for(File myFile : files){
    CompletableFuture.supplyAsync(() -> MyFileService.resize(myfile))
}

For CompletableFuture.supplyAsync default will use ForkJoinPool common pool, the default thread size is: Runtime.getRuntime().availableProcessors() - 1, also you can modify this by:

  1. System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", size)
  2. Djava.util.concurrent.ForkJoinPool.common.parallelism=size

also you can use supplyAsync method with your own Executor, like:

ExecutorService executorService = Executors.newFixedThreadPool(20);
CompletableFuture.supplyAsync(() -> MyFileService.resize(myfile), executorService)
like image 85
chengpohi Avatar answered Sep 29 '22 20:09

chengpohi


The "most simple" straight forward solution is to create a "bare metal" Thread on the fly and have it call that method. See here for details.

Of course, programming is always about adding levels of abstractions; and in that sense, you can look into using an ExecutorService. And as you are mentioning java8, this here would be a good starting point (that also shows how to use ordinary Threads in a more java8 style).

like image 28
GhostCat Avatar answered Sep 29 '22 21:09

GhostCat


Most simple would be (with Java 8):

for(File myFile : files){
  new Thread( () -> MyFileService.resize(myfile)).start();
}
like image 26
Thomas Philipp Avatar answered Sep 29 '22 19:09

Thomas Philipp