So I was going through the internal working of Executor Service, and in the constructor of thread there were these lines mentioned:
Thread(ThreadGroup g, String name, int characteristics, Runnable task,
long stackSize, AccessControlContext acc) {
Thread parent = currentThread();
boolean attached = (parent == this); // primordial or JNI attached
So my question here is, how is it possible that current running thread is equal to the new instance of thread ?
The currentThread()
is returning ... the currently executing thread.
In the Thread
constructor, this
will be the Thread
object that is being constructed. This is not normally the executing thread. The Thread
you are creating here normally starts executing when something calls start()
on it.
However ... here are a couple of scenarios when that is not true.
One scenario occurs when bootstrapping the JVM. Bootstrapping involves creation of certain Java objects before all of the JVM infrastructure is working. One of these objects is the Thread
object for the primordial thread; i.e. thread that is doing the bootstrapping. The bootstrapping code will do something like this:
Thread
object without running its constructor. (It can do that: it is implemented in native code.)currentThread()
returns the Thread
object.Thread
object with the appropriate parameters.If you want to trawl through the OpenJDK source tree, you should be able to find the code that does this. It is complicated.
According to that comment, other scenarios apparently involve JNI. I'm not sure, but it could happen when a C or C++ application calls JNI_CreateJavaVM
.