Threads and lifecycle question 1 of 180 junior
What is the difference between a process and a thread, and what does that cost you in Java?
- Threads have separate heaps, processes share one
- Correct: Threads of one process share heap and metaspace but each has its own stack and program counter
- A thread cannot have its own local variables
- Processes are always faster to create than threads
A process owns an address space. Threads inside it share the heap, static fields and open file descriptors, and each gets its own stack, program counter and thread-local storage. That sharing is exactly why concurrency in Java is hard: two threads reach the same object with no coordination unless you add some.
The cost side matters in interviews. A platform thread in HotSpot is a 1:1 mapping onto an OS thread,
with a reserved stack (1 MB by default on 64-bit Linux, -Xss to change it) and a context switch that
goes through the kernel. That is why a thread per request stops scaling in the thousands, and why
virtual threads exist.