(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.
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.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
packagecom.karlsangabriel.waitallthreads;
publicclassThreadTestimplementsRunnable
{
privateThreadWaitBean waitBean;
publicThreadTest(ThreadWaitBean bean)
{
this.waitBean=bean;
}
publicvoidrun()
{
System.out.println(
this.toString()+" task has started");
try
{
Thread.sleep(10000);
}
catch(InterruptedExceptione)
{
e.printStackTrace();
}
System.out.println(this.toString()
+" completing task");
this.waitBean.executionComplete();
this.waitBean=null;
}
}
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.
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
packagecom.karlsangabriel.waitallthreads;
publicclassWaitAllThreadsMain
{
publicstaticvoidmain(String[]args)
{
ThreadWaitBean waitBean=newThreadWaitBean();
waitBean.setExpectedCount(5);
for(inti=0;i<waitBean.getExpectedCount();i++)
{
Threadt=newThread(newThreadTest(waitBean));
t.start();
}
while(!waitBean.isDone())
{
try
{
Thread.sleep(1000);
}
catch(InterruptedExceptione)
{
Thread.currentThread.interrupt();
e.printStackTrace();
}
System.out.println(
"Parent thread awaits Threads completion");
}
System.out.println("All Threads completed at this point");
}
}
Demo and Output
We will get the following in our console if we run the codes.
This concurrency implementation was a significant source of concurrency bugs as far as I can remember. Therefore, I rewrote it.
223 total views
, 1 views today
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!.