Abichellam
Abichellam

Reputation: 509

Alternate to Busy-Wait

In my application, Jobs will be submitted dynamically, I need to keep track of submitted job's completion. While I shutdown my application, I want to wait till all the submitted jobs completed. For this I maintain a list of submitted job ids. As soon as process completion notification is raised, I remove the id from the list. When shutdown is called, I am waiting till the list becomes empty.

while (!ids.isEmpty());

Is there a better way to this busy wait.

Upvotes: 0

Views: 4225

Answers (3)

Stephen C
Stephen C

Reputation: 719229

If you are implementing the job dispatching and running by hand by creating and starting threads, then you need to use Object.wait and Object.notify to implement a condition variable. It is a bit fiddly to get right ...

But a better approach is to use a ThreadPoolExecutor service for running your jobs. That allows you to submit all of the jobs, and then call shutdown and awaitTermination ... which will wait until all of the queued jobs have completed.

Upvotes: 1

Roy Kazz
Roy Kazz

Reputation: 21

You could try to do it the other way around: Each job calls an "exit"-method (in the class that holds the ids) that checks if this is the last process to die. Then there will be no busy-wait loop. Provide each job with an "TerminationHandlerInterface" that have the exit-method.

Upvotes: 0

meriton
meriton

Reputation: 70574

Are you reinventing an ExecutorService? In particular, its awaitTermination() method? And yes, awaitTermination() does not busy wait ...

Upvotes: 0

Related Questions