简体   繁体   中英

Right way to execute 2 independent tasks in Java

I have 2 independent tasks to execute. I need the result of Task1 first followed by task2.

Which of the below 2 ways is better in terms of number of threads and performance(if at all) and why? Will there be any performance difference between the 2 methods?

Method1:

1. Execute Task1 & Task2 asynchronously by submitting them to ExecutorService
2. Get the results by calling future1.get() followed future2.get()

Method2:

1. Execute task2 asynchronously by submitting it to ExecutorService.
2. Execute Task1 on main thread
3. Get the result of task2 by calling future2.get()

The first is better from human point of view:

  • Task 1 and Task 2 are equivalent tasks
  • Both are executed as secondary tasks
  • You explicitly define the order of threads to wait

The second is better from jvm point of view:

  • There is just one external thread added to the main thread (instead of 2)
  • You wait only for the second result

But generally over optimize the code is not a good idea if the resulting code is less human readable. My tip is:

Don't optimize the code if not needed.

I would think method 1 is preferable. You are kicking off both tasks, then telling the compiler that you have nothing else to do until both tasks complete. Once both tasks are complete you can proceed. You leave any decisions/optimisations on how to run the tasks to the JVM which is best positioned to make those decisions.

I would suspect that there is little difference with respect to threads, processing time, etc. to either approach once the code is compiled and optimised by the JVM - the 'work' to be done is the same either way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM