When I say something like:
Thread t1 = new Thread();
does it create it on a heap or a stack?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With