Video in progress

Explain the difference between heap and stack memory.

Stack / Heap — Who owns it: each thread has its own / shared by all threads; What it stores: frames: local variables, parameters, return address / objects, arrays; Who cleans it: the frame disappears when the method ends / the garbage collector; Size: small (-Xss, usually 512KB-1MB) / large (-Xmx); Error…

📖 Answer

Stack Heap
Who owns it each thread has its own shared by all threads
What it stores frames: local variables, parameters, return address objects, arrays
Who cleans it the frame disappears when the method ends the garbage collector
Size small (-Xss, usually 512KB-1MB) large (-Xmx)
Error StackOverflowError OutOfMemoryError: Java heap space
void handle() {
    int count = 5;                 // on the stack
    Order order = new Order();     // the order reference is on the stack, the Order object is on the heap
}

Because the stack is per-thread, local variables are thread-safe. An object on the heap can be seen by several threads, and that is where synchronization comes in.