When JVM is started OS allocates memory to it and then that memory is used as the heap and the stack. When we create an object in the heap, what happens to the object after the JVM exits? Does it quietly stay there and OS reallocates that memory when JVM restarts? Or does something else happen?
What happens to the Objects in the heap when JVM exits?
219 Views Asked by Shubhamhackz At
2
There are 2 best solutions below
0

Objects in the heap are freed when the JVM exits (most of the time).
The reason I say most of the time is because freeing the heap is the responsibility of the operating system, not the JVM alone. The operating system does the effort of cleaning up and making memory allocations available for leasing. But this also depends on the operating system, I'm sure there are operating systems out there where they don't follow this mainstream method.
Most objects simply "evaporate" when the JVM exits — i.e., they vanish without the normal garbage collection process (including finalization) taking place. (It is possible to request finalization for them, but it is unwise because they may still be reachable and in use.) If those objects represent OS resources like open files, those resources are released (closed), but without guaranteeing that all outstanding data is saved (as happens when you close them yourself).
More generally, when a process exits, all of its normal stack and heap memory is immediately freed by the OS (although some of it, like that used to store the executable and other files that were read, can sometimes be reused (or left in use) for other processes that need those files). Exceptions include things like shared memory used for interprocess communication, which you're probably not using without knowing it.