Java, Software Development

(Bad Practice) Wait Until All Threads Complete Execution in Java

This post shows an example of a bad practice I saw in one of my Java projects seven years ago. It also has a naive implementation of concurrency in Java, wherein it waits for all threads to complete. Moreover, it tracks the number of started, completed, and in-progress threads. Since the codes exhibit malpractice, I do not recommend using these codes. Alternatively, there are better solutions already available in the Java SDK.

A Wait Bean For All Threads To Complete

This class keeps count of expected, and completed threads count.

The Thread class

This class represents a task. It sleeps for 10 seconds to simulate heavy processing and runs the executionComplete method. Therefore, all our Java threads will wait 10 seconds before they are complete.

Main Class That Starts All Java Threads

The codes need to know the number of Java threads to process or complete. The ThreadWaitBean keeps this number of started threads compared to the number of threads actually completed. The basic idea is that each thread has access to a single ThreadWaitBean object. Right before a thread ends, it runs the executionComplete method. That method adds 1 to the number of threads actually completed.

Demo and Output

We will get the following in our console if we run the codes.

Sample output

This concurrency implementation was a significant source of concurrency bugs as far as I can remember. Therefore, I rewrote it.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like