0 votes
in JAVA by
Is exceeding the memory limit possible in a program despite having a garbage collector?

1 Answer

0 votes
by
Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them.

In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.

Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavours its level best to reclaim memory as much as possible, memory limits can still be exceeded.

Let’s take a look at the following example:

List<String> example = new LinkedList<String>();

while(true){

example.add(new String("Memory Limit Exceeded"));

}

Related questions

+1 vote
asked Jan 24, 2020 in JAVA by rahuljain1
+1 vote
asked May 5, 2021 in JAVA by SakshiSharma
...