1

Consider a very short program where I am allocating a little bit of memory. I have been taught that GC runs in circumstances when a program allocates a lot of memory and the allocation reaches a limit.

I don't know what that limit is exactly but I think it must be high enough so that GC doesn't run frequently and slows down the execution of the program.

My question is, what happens when the allocation doesn't reach the level at which GC prepares to run, during the lifetime of a program. Does it results in a memory leak?

3 Answers3

1

Nothing specific happens. Roughly saying: memory allocated for java process returns to the heap. More specifically: JVM uses native memory for allocating memory for java process. After java process terminates this memory becomes free for other processes in the Operating System. I suggest you read more about this things e.g. here: http://www.ibm.com/developerworks/library/j-nativememory-linux/

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
1

Garbage collection doesn't run only when there is no more memory, a parallel collector actually runs in another thread and collects when it determines it has time to do so, but that's not the only strategy.

See Java garbage collector - When does it collect?

Community
  • 1
  • 1
Adel Khial
  • 345
  • 4
  • 15
0

If your question is: what happens to the memory if your JVM ends before the GC is running?

Very simple: the complete memory is "returned" to the operating system and becomes available to that again.

In simple words:

  1. When you start your JVM, xx MB of memory are given to it
  2. When your JVM finds that it runs out of memory, the GC kicks in, to get rid of garbage (so that the JVM can continue to run)
  3. When your JVM exits, those xx MB go back to the operating system

For step 3, it is absolutely irrelevant if/how often step 2 happened.

Finally: "heap" is how the JVM internally uses memory. The OS just knows about the absolute memory chunks it gave to the JVM.

GhostCat
  • 137,827
  • 25
  • 176
  • 248