3

In my method, I have to call another method (AnotherMethod) that returns a future.

eg.

private static void myMethod() {
    Future<MyObj> mjObj = AnotherMethod();
    return;
}

I don't actually care about the value returned by AnotherMethod (eg. the value of myObj), but I do want AnotherMethod to run fully.

If I discard the reference to the future (as in the above example), will AnotherMethod still finish running?

I understand it won't finish before returning from myMethod, but will it still complete at some point even though there's no reference to myObj anymore?

oxuser
  • 1,257
  • 2
  • 16
  • 23
  • 3
    There is no guarantee that a future will ever run. But if you create it, say, via an executor, then the executor still has a reference to it. – Andy Turner Aug 09 '18 at 17:11
  • 4
    Really depends on what `AnotherMethod()` does, simply creating a Future does not run it (as in `new Future()` - that's just a boring Object). If that method on the other hand sends some task to an `Executor` then it's referenced by the task queue and eventually executed. – zapl Aug 09 '18 at 17:11
  • Possible duplicate of [Java Concurrency: Is cancelling Futures necessary for them to be Garbage Collected?](https://stackoverflow.com/questions/20135304/java-concurrency-is-cancelling-futures-necessary-for-them-to-be-garbage-collect) – Randy L Aug 09 '18 at 19:07

1 Answers1

2

First of all, AnotherMethod always will be performed from the start to the end because you call it. As for concurrency, if AnotherMethod starts a Thread or submits task to an executor then this concurrent execution will not be interrupted. Garbage collector does not interrupt threads because they are GC roots - top level objects in JVM.

jreznot
  • 2,694
  • 2
  • 35
  • 53