ansme
ansme

Reputation: 463

How does Garbage Collector frees up memory before JVM exits?

I've read that Garbage Collector runs as a daemon thread in java, and daemon threads have low priority and they run in the background supporting other non-daemon threads and that's why JVM doesn't wait for daemon threads to finish their execution.

In a situation where if all non-daemon threads have exited but there's still some amount of memory occupied then how does Garbage Collector manage to free up resources before the JVM stops without causing any memory leaks?

Upvotes: 1

Views: 511

Answers (1)

Stephen C
Stephen C

Reputation: 718768

The GC does NOT free up memory before the JVM exits.

What actually happens is that when the JVM exits, the process that the JVM runs in also exits1. When the process exits, the operating system reclaims all of the RAM and swap pages that the process was using (exclusively) and reclaims its virtual memory page tables.

If your Java program (or C / C++ program) has memory leaks, that doesn't matter once the process is cleaned up. The OS knows at all time which RAM / swap pages belong to which process. Nothing is lost.


1 - If the JVM was started by a C / C++ application using (say) JNI, then the process won't necessarily exit at that point. It would then be up to the C / C++ application to figure out what to do. But the GC doesn't clean up in this case either.

Upvotes: 5

Related Questions