问题
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?
回答1:
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:
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", size)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)
回答2:
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).
回答3:
Most simple would be (with Java 8):
for(File myFile : files){
new Thread( () -> MyFileService.resize(myfile)).start();
}
来源:https://stackoverflow.com/questions/41057655/best-way-to-execute-simple-async-task-in-java