azuri azuri - 5 months ago 17
Java Question

Java Thread join creates sequential running of threads

When i run the following code, the program never exits and gets stuck in the while loop which should be the expected behaviour.

public class MyClass implements Runnable {
public static final int NO_OF_THREADS = 100;
private static int count;
private static Set<Integer> set = new HashSet<>();
public void run() {
for(int i=0 ;i<10000; i++) {
public static void main(String[] args) throws Exception {
Thread[] threadArray = new Thread[NO_OF_THREADS];
for(int i=0; i<NO_OF_THREADS; i++) {
threadArray[i] = new Thread(new MyClass());
for(int i=0; i<NO_OF_THREADS; i++) {
while(set.size()!=1000000) {}

With the join() uncommented the program always exits. Moreover, When I modified the code to print the the sequence in which the threads run, with the join in place, I observed that Thread-0 first completes its task followed by Thread-1 and so on in proper numbering sequence.

Is this expected behaviour or just one of the idiosyncrasies of the JVM

Answer Source

yes this is the expected behavior, with your join commented, more than thread will have access to your set in the same time, you will have race condition , in a case where count will be the same for more than thread so basically you will be adding more than one element in the same place so you will not have your expected number of items in the set hence the loop condition will always be true and your app wont exit.

with your join not commented, main thread will be blocked until each thread is finished, when the first thread starts and the main thread moves to the join, the main thread will be blocked and wait the first thread to finish before moving to the next iteration of the loop, so you wont have any concurrent access to "count" hence all the added elements will be different