Search code examples
javafutureexecutorservicejava-threadscallable

How to see which thread(name) was executed from a future object


The code below is what I make an instance of an submit to executor service and its result is what i store in a future object. Is there any way I can see the name of the thread that gave the result from the future object. For example, if thread 1 return an Integer value of 4 and that value is stored in a future object. How can I tell that thread 1 was the one that executed and returned that value of 4? Please feel free to clarify if I did not explain properly.

class Test implements Callable<Integer>{
  Integer i;
  String threadName;

   public Test(Integer i){
     this.i = i;
   }

  public Integer call() throws Exception{
    threadName = Thread.currentThread().getName();
    System.out.println(Thread.currentThread().getName());
    Thread.sleep(i * 1000);
    return i ;
  }

  public String toString(){
    return threadName;
  }
}

Solution

  • Instead of an Integeryou can return an object that contains the result and the name of the thread:

    public static class ResultHolder {
        public Integer result;
        public String threadName;
    }
    
    [...]
    
    public ResultHolder call() throws Exception {
        ResultHolder ret = new ResultHolder();
        ret.threadName = Thread.currentThread().getName();
        ret.result = i;
        Thread.sleep(i.intValue() * 1000);
        return ret;
    }