Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does garbage collection guarantee that a program will not run out of memory?

Tags:

java

I heard most elegant property of java is Garbage Collection I wanna know does it guarantee that a program will not run out of memory?

like image 527
giri Avatar asked Jan 19 '10 22:01

giri


2 Answers

No, it's always possible that you'll try to allocate more memory than is available.

Automatic garbage collection only means that garbage (i.e., unreferenced memory) is automatically collected (i.e., reclaimed for further use). If you keep references to it, it's not garbage, and not collected.

like image 152
Ken Avatar answered Oct 14 '22 16:10

Ken


No it does not guarantee this. It is perfectly possible for a programmer to mistakingly create objects which never go out of scope, thus consuming more and more memory until all heap is exhausted.

It is the programmer's responsibility to ensure that objects no longer in use are no longer referenced by the application. That way the garbage collector can do its job and reclaim memory used by these objects.

Example

public class Main {
  public static void main(String[] main) {
    List<String> l = new LinkedList<String>();

    // Enter infinite loop which will add a String to
    // the list: l on each iteration.
    do {
      l.add(new String("Hello, World"));
    } while(true);
  }
}
like image 36
Adamski Avatar answered Oct 14 '22 15:10

Adamski