Best way to execute simple async task in Java?

我怕爱的太早我们不能终老 提交于 2019-12-23 16:45:56

问题


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:

  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)



回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!