Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread synchronization question (in java)

my java application has a loading task which requires two server calls which can be parallelized. So I launch a Thread t1 (doing task1) and a Thread t2 (for task2). I want then to do a specific task, task3 when both other tasks (1 & 2) are over. Naturally I can't tell which of task1 and task2 will finish first...

Which would be for you the simplest (and safest) way to code this ?

Thank you for your help

like image 459
Laurent K Avatar asked Jan 24 '23 01:01

Laurent K


2 Answers

You've got several options:

  1. If task3 is on a separate thread AND task1 and task2 threads are exclusive to their tasks (no thread pooling) and finish when the task finish, you can use {T1.join(); T2.join();} to wait for both threads. Pros: Easy. Cons: The situation is rarely that simple.
  2. If task3 is on a separate thread, you could use java.util.concurrent.CountDownLatch shared between all threads. Task 3 will wait for the latch while task1 and task2 will decrease it. Pros: quite easy, oblivious to the environment. Cons: require T3 to be created before it's really needed.
  3. If task3 should only be created AFTER task1 and task2 are finished (no separate thread for it until after task1 and task2 finishes), you'd have to build something a bit more complex. I'd recommend either creating your own ExecutorService that take a condition n addition to the future and only executes the future when the condition changes, or creating a management service that will check conditions and submit given futures based on these conditions. Mind, this is of the top of my head, there might be simpler solutions. Pros: resources-friendly. Cons: complex.
like image 122
Ran Biron Avatar answered Jan 29 '23 06:01

Ran Biron


You can join both t1 and t2 (in either order), then run task3 after the join.

like image 27
Chris Jester-Young Avatar answered Jan 29 '23 06:01

Chris Jester-Young