0

In the source code of FutureTask<V>, there is a volatile instance variable Thread runner, where the comment told that it is the thread running the callable. However, the runner is never initialized in the source code. Moreover, I could not find any clue how this runner is used to run the callable.

Question: Since the runner is never initialized, how it is used to run the Callable?

Rui
  • 3,454
  • 6
  • 37
  • 70
  • In the source listing you link to there's some calls to `sun.misc.Unsafe` with the `runner` field. I assume the field is initialized by native code. `UNSAFE.objectFieldOffset(k.getDeclaredField("runner"));` – markspace Sep 30 '18 at 19:08
  • @markspace, I think you mean places like `UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread()))`. `objectFieldOffset` just returns field offset. – awesoon Sep 30 '18 at 19:12

1 Answers1

1

In the code you can see

if (state != NEW ||
        !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                     null, Thread.currentThread()))

at the start of the run method. Ignoring the state != NEW part; this attempts to set the runner variable to the result of Thread.currentThread() (and will succeed only if it is currently null). Only if this succeeds (returns true) will the run method be able to go through the rest of the code in this block. And since the result of Thread.currentThread() will be the Thread which called the run method, the documentation is accurate (at least, after this initial if part is successfully evaluated).

BeUndead
  • 3,463
  • 2
  • 17
  • 21
  • Thanks a lot :) In addition to this, I feel that the FutureTask is like a proxy to the Callable (subject), isn't it? – Rui Sep 30 '18 at 19:32
  • @Rui , yes, to some extent. The _result_ of the `FutureTask` is obtained by invoking the `Callable`; however there is additional functionality added (reporting, only being callable _once_, etc.) which is not provided by the simple `Callable` item. – BeUndead Sep 30 '18 at 19:43
  • It's also worth noting that this is only a single implementation of `FutureTask`. Other JDK implementations may choose to _not_ delegate to a `Callable` (although I suspect pretty much all sane ones would). – BeUndead Sep 30 '18 at 19:44