Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is runnable object garbage collected in ExecutorService?

I have a runnable object A which exchanges heart beat signals with a server on instantiation. I submit n such objects to a executor service with fixed thread pool size of n. When the run method encounters exception it would return. For a given case, all my threads encounter exception and return, but the object created remains alive and keeps on exchanging the heart beat signals. How do I mark such objects up for garbage collection so that they would stop the heart beat signals exchange?

class A implements Runnable {
    public void run(){
          try{
           \\throws error
          } catch(Exception e){
            \\returns
          }
       }

    public static void main(){
          ExecutorService executor = Executors.newFixedThreadPool(n)
          for(i = 1 to n){
               A a = new A()
               executor.submit(a)
          }
       }
}

Should I put a awaitTermination call at the end of my main and do a return?

Edit:
Putting the question other way, one way to terminate the executorservice after all the threads return would be to call shutdown() after the for loop and call awaitTermination with Integer.MAX long seconds which is roughly 70 years ( which is a time constraint I am reluctant to impose). Is there any other alternative?

like image 500
ankshah Avatar asked Nov 09 '22 03:11

ankshah


1 Answers

one way to terminate the executorservice after all the threads return would be to call shutdown() after the for loop and call awaitTermination with Integer.MAX long seconds which is roughly 70 years

as the doc says the awaitTermination method will block util:

  1. all tasks have completed execution after a shutdown request
  2. or the timeout occurs,
  3. or the current thread is interrupted, whichever happens first


So it will game over as soon as one of the three event turn up, rather than have to wait 70 years.

like image 105
nail fei Avatar answered Nov 14 '22 21:11

nail fei