Method reference in a Runnable makes object GC safe?

Adwait Kumar :

For example in the given code,

@Singleton
public class MyExecutor {

  ExecutorService executorService;

  public void execute(Runnable runnable) {
    executorService.submit(runnable);
  }
}

class A {
  public void a(String x) {
    // do something
  }

  MyExecutor executor;

  // Injected via DI, always is same object
  A(MyExecutor executor) {
    this.executor = executor;
  }

  public void run() {
    executor.execute(() -> a("Whatever"));
  }
}

So my question is suppose I am creating As very frequently and calling their a.run() and then forgetting about it, will my A object not be collected by the GC till MyExecutor has finished processing with them?

It seems to me this should be the case, other wise how will MyExecutor ever know which instance to execute?

So basically my question is, does a caller object passing a instance method reference as a Runnable/Callable/Consumer..etc be GC safe till the passed Runnable/Callable/Consumer has someone holding a reference to them?

GhostCat salutes Monica C. :

Sure.

It is very simple: as long as an "active" object keeps a reference to some other object X, that other object X isn't eligble for garbage collection.

And it is safe to assume that an executor keeps track of all tasks submitted to it. When the task is finished, any reference to the task/runnable passed to it ... is no longer needed. So the executor forgets about it, and then that task/runnable becomes eligible for GC.

And please note: there are no "method reference" objects! Method references or lambdas are basically objects of some class (Task or Runnable, depending on context for example). Method references are first of all a syntax element!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=83493&siteId=1