executorservice - Java ThreadFactory: Why does one use of works but other doesn't? -


in following program code hangs while trying get() on future in method second()! why that? difference between 2 executor services threadfactory use. doesn't matter if use newsinglethreadexecutor or newfixedthreadpool count of 1.

package me.test; import java.util.concurrent.callable; import java.util.concurrent.executionexception; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.future; import java.util.concurrent.threadfactory;  public class executorservicetest {     threadfactory tf1 = new threadfactory() {         @override         public thread newthread(runnable r) {             thread t = executors.defaultthreadfactory().newthread(r);             t.setdaemon(true);             t.setname("tf1-thread");             return t;         }     };     threadfactory tf2 = new threadfactory() {         @override         public thread newthread(runnable r) {             thread t = new thread("tf2-thread");             t.setdaemon(true);             return t;         }     };     executorservice service1 = executors.newsinglethreadexecutor(tf1);     executorservice service2 = executors.newsinglethreadexecutor(tf2);     callable<integer> callable = new callable<integer>() {         @override         public integer call() throws exception {             return 0;         }     };      public static void main(string[] args) throws executionexception, interruptedexception {         executorservicetest executortest = new executorservicetest();         executortest.first(); // returns         executortest.second(); // hangs         system.exit(0);     }      void first() throws executionexception, interruptedexception {         future<integer> future = service1.submit(callable);         int result = future.get();         system.out.println("result=" + result);     }     void second() throws executionexception, interruptedexception {         future<integer> future = service2.submit(callable);         int result = future.get();         system.out.println("result=" + result);     } } 

your first factory creates thread runs specified runnable:

thread t = executors.defaultthreadfactory().newthread(r); 

whereas in second factory forgot provide runnable created thread:

thread t = new thread("tf2-thread"); 

so, in second case, runnable never run, , future never gets value.

change thread creation in second case to

thread t = new thread(r, "tf2-thread"); 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -