Making Callable Threads as Daemon
java, multithreading
Solution
How can I make Callable thread as daemon thread?
You need to use a new `ThreadFactory` that creates daemon threads. See this answer here: Executor and Daemon in Java
By default the executors create non-daemon threads whenever they build their pools. But you can inject your own `ThreadFactory` which creates the threads for the pool.
For example:
executor = ExecutorService.newSingleThreadExecutor(new MyThreadFactory());
The `ThreadFactory` implements the `newThread` method:
Thread newThread(Runnable r)
Copied from the answer I linked to above, you could implement it like:
class MyThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
}
You mentioned in your question:
//Thread.currentThread().setDaemon(true);
Yeah, this won't work because you cannot set the daemon flag once the thread has been started.
Problem
How can I make Callable thread as daemon thread? Here is what I am trying. I am trying to execute a set of threads of which one of them does not complete and goes into infinite loop. What it does is the main thread of the program does not terminate even though all the code statements are executed. The main thread goes into suspended mode after that. Here is the code snippet for the same. ``` public class MyThread implements Callable<String> { private int value; public MyThread(int value) { this.value = value; } @Override public String call() throws Exception { //Thread.currentThread().setDaemon(true); System.out.println("Executing - " + value); if (value == 4) { for (; ; ); } return value + ""; } } ``` Main Program ``` public class ExecutorMain { public static String testing() { ExecutorService executor = null; List<Future<String>> result = null; String parsedValue = null; try { executor = Executors.newSingleThreadExecutor(); List<MyThread> threads = new ArrayList<MyThread>(); for (int i = 1; i < 10; i++) { MyThread obj = new MyThread(i); threads.add(obj); } result = executor.invokeAll(threads, Long.valueOf("4000"), TimeUnit.MILLISECONDS); //result = executor.invokeAll(threads); for (Future<String> f : result) { try { parsedValue = f.get(); System.out.println("Return Value - " + parsedValue); } catch (CancellationException e) { System.out.println("Cancelled"); parsedValue = ""; f.cancel(true); } } executor.shutdownNow(); } catch (Exception e) { System.out.println("Exception while running threads"); e.printStackTrace(); } finally { List executedThreads = executor.shutdownNow(); System.out.println(executedThreads); for (Object o : executedThreads) { System.out.println(o.getClass()); } } System.out.println("Exiting...."); //System.exit(1); return ""; } public static void main(String[] args) { testing(); } } ``` What I got to understand from my earlier question about Dangling threads in Java is that I have to make my threads as daemon threads.