I am trying to create an application , which will create threads in a tree like manner.My main method is at Level0 , which creates thread in Level1 .Then Level1 will create some threads. Each threads in Level1 , will create different sets of threads as Level2 , and so on.
Below is the code that I am trying to use , using ExecutorService :
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ThreadTree {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
//This is the main , level0
List ll = new ArrayList<>();
ll.add(2);
ll.add(5);
ll.add(8);
Iterator it = ll.iterator();
while (it.hasNext()) {
exec.submit(new Level1((Integer)it.next()));
}
}
}
class Level1 implements Runnable{
private ScheduledExecutorService exec;
private Integer num;
public Level1(Integer n){
num = n;
exec = Executors
.newScheduledThreadPool(n);
}
@Override
public void run() {
for(int i=0;i<num;i++){
exec.scheduleAtFixedRate(new Level2(), 0, 2, TimeUnit.SECONDS);
}
}
}
class Level2 implements Runnable{
@Override
public void run() {
System.out.println("Current Thread ID : " + Thread.currentThread().getId() + "Current Thread Name : "
+ Thread.currentThread().getName()) ;
//Do some task and create new threads
}
}
I have 2 questions :
- Is this the only approach to create the threads in a tree manner? Are there any other ways to handle this effectively, with some grouping? I have shown 3 levels , but there can be more levels also.
- In case, this is a good way, what is the best way to propagate any failure in a thread in one of the levels the layer above it and so on.
Thanks in advance.
I think you can achieve this by following the steps below -
Runnable
object whileThread
is a Java thread that executes the runnable task through executor.)Please refer the sample below -
Here
Notification
is being passed fromLevel3
->Level2' ->
Level1'. Every child task has a duty to notify parent once it is done with its own job. Once all child tasks have notified the parent task will do the post run actions and notify its parent.Here it does not matter which threads are being used from thread pool executor. The only thing that matters is following the rule of notification to parent by every child task and then parent doing post actions and further notifying its parent.
Notification
class consists onresult
androotException
which can be set from child task so that parent can know what went wrong in child task and the exception can travel up to top level.