Home > Enterprise >  Right way to execute 2 independent tasks in Java
Right way to execute 2 independent tasks in Java

Time:09-14

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()

CodePudding user response:

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.

CodePudding user response:

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.

  • Related