Monday 14 July 2014

When to join threads, concurrency, sequentially & When to join threads with CountDownLatch



Let's say I need to spawn multiple threads to do the work, and continue to the next step only after all of them complete. I will need to tell the main thread to wait. The key point is to use Thread.join() method. For example,


threadsJoinWithConcurrency();
textView.setText(threadNames.toString());

===========================================

public void threadsJoinWithConcurrency() {
List<Thread> threadList = new ArrayList<Thread>();

Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
 for (int i = 0; i < 1000000; i++) {
 i = i + 0;
}
threadNames.add("Thread-1");
}
});
threadList.add(t1);

Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
  i = i + 0;
 }
 threadNames.add("Thread-2");
}
});
threadList.add(t2);

Thread t3 = new Thread(new Runnable() {
@Override
public void run() {

 for (int i = 0; i < 1000000; i++) {
  i = i + 0;
  }
 threadNames.add("Thread-3");
}
});
threadList.add(t3);

for (Iterator<Thread> iterator = threadList.iterator(); iterator.hasNext();) {
 Thread thread = iterator.next();
 thread.start();
}

for (Iterator<Thread> iterator = threadList.iterator(); iterator.hasNext();) {
 Thread thread = (Thread) iterator.next();
 try {
 thread.join();
 } catch (InterruptedException e) {
  e.printStackTrace();
 }
 }
}


The output when running this program with 10 threads:

[Thread-1, Thread-3, Thread-2,]

The order in which the threads are executed is random, which is expected.

Also note that we use two for-loops, the first to create and start each thread, and the second loop to join each thread. If each thread is joined right after start, the effect is these threads are executed sequentially, without the desired concurrency. For example, the following code snippet results in serial execution:


threadsJoinWithSequentially();
textView.setText(threadNames.toString());

===================================

public void threadsJoinWithSequentially() {
List<Thread> threadList = new ArrayList<Thread>();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
 for (int i = 0; i < 1000000; i++) {
   i = i + 0;
 }
 threadNames.add("Thread-1");
}
});
threadList.add(t1);

Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
   for (int i = 0; i < 1000000; i++) {
   i = i + 0;
  }
 threadNames.add("Thread-2");
}
});
threadList.add(t2);

Thread t3 = new Thread(new Runnable() {
@Override
public void run() {

for (int i = 0; i < 1000000; i++) {
 i = i + 0;
 }
 threadNames.add("Thread-3");
 }
 });
 threadList.add(t3);

for (Iterator<Thread> iterator = threadList.iterator(); iterator.hasNext();) {
 Thread thread = iterator.next();
 thread.start();
 try {
 thread.join();
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
}
}

Output:
[ Thread-1, Thread-2, Thread-3]

If we don't use any join at all, threadNames, when printed, may be empty, or partially filled, since the main thread will just move on when it gets the chance. The main thread will still wait, at the very last step, for all threads to complete, before exiting the JVM. The output for running 10 threads may be:

[Thread-1, Thread-2]

...

Thread.join() is used to wait for all child threads to complete. Now I will update it using CountDownLatch instead:

threadsJoinCountDownLatch();
textView.setText(threadNames.toString());

=====================================

public void threadsJoinCountDownLatch() {
List<Thread> threadList = new ArrayList<Thread>();
final CountDownLatch latch = new CountDownLatch(3);

Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
 for (int i = 0; i < 1000000; i++) {
   i = i + 0;
  }
  threadNames.add("Thread-1");
  latch.countDown();
  }
});
threadList.add(t1);

Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
 for (int i = 0; i < 1000000; i++) {
   i = i + 0;
 }
   threadNames.add("Thread-2");
   latch.countDown();
   }
});
threadList.add(t2);

Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
  for (int i = 0; i < 1000000; i++) {
    i = i + 0;
   }
   threadNames.add("Thread-3");
   latch.countDown();
  }
});
threadList.add(t3);

 for (Iterator<Thread> iterator = threadList.iterator(); iterator.hasNext();) {
   Thread thread = iterator.next();
   thread.start();
 }

 try {
   latch.await();
 } catch (InterruptedException e) {
   e.printStackTrace();
}
}

A CountDownLatch is created in main thread, passed to each child thread's constructor. Each child thread will count down by 1. After starting all child threads, the main thread then wait for the latch count to reach 0. To run it:
[ Thread-2, Thread-0, Thread-3]


I hope it will helpful :) Happpppy codddding :)