Where is Thread Object created? Stack or Heap?

There is no way to allocate objects on the stack in Java.
The stack can only hold references and primitives, and only for local variables.

Note that starting a thread will create a new stack for that thread.


Thread t1 = new Thread();

tl;dr This allocates object i.e. t1 in heap.

As each new thread comes into existence, it gets its own pc register (program counter) and Java stack. If the thread is executing a Java method (not a native method), the value of the pc register indicates the next instruction to execute. A thread's Java stack stores the state of Java (not native) method invocations for the thread. The state of a Java method invocation includes its local variables, the parameters with which it was invoked, its return value (if any), and intermediate calculations. The state of native method invocations is stored in an implementation-dependent way in native method stacks, as well as possibly in registers or other implementation-dependent memory areas.

The Java stack is composed of stack frames (or frames). A stack frame contains the state of one Java method invocation. When a thread invokes a method, the Java virtual machine pushes a new frame onto that thread's Java stack. When the method completes, the virtual machine pops and discards the frame for that method.

The Java virtual machine has no registers to hold intermediate data values. The instruction set uses the Java stack for storage of intermediate data values.

Figure shows a snapshot of a virtual machine instance in which three threads are executing. At the instant of the snapshot, threads one and two are executing Java methods. Thread three is executing a native method. It also shows of the memory areas the Java virtual machine creates for each thread, these areas are private to the owning thread. No thread can access the pc register or Java stack of another thread.

enter image description here


In Java 8, using Escape Analysis objects can be created on the stack. This occurs when an object is detected as not escaping the current method (after inlining has been performed) Note: this optimisation is available in Java 7, but I don't think it worked as well.

However, as soon as you call start() it will escape the current method so it must be placed on the heap.

When I say something like:

Thread t1 = new Thread();

does it create it on a heap or a stack?

It could place it on the stack, provided you don't use it to create a real thread. i.e. if you so

Thread t1 = new Thread(runnable);
t1.start();

It has to place it on the heap.