Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Java has garbage collection, then why does OutOfMemoryError occur? [duplicate]

This is a theoretical question. I am just curios that if Java has a mechanism for garbage collection to free the memory, then why does still OutOfMemoryError occur?

I searched SO for this but could get these links

Is the garbage collector guaranteed to run before Out of Memory Error?

Garbage collection before OutOfMemoryError

These do not answer my question specifically. If Java allows memory so well by using garbage collection, then why does OutOfMemoryError occur?

like image 650
Prasad Kharkar Avatar asked Jun 25 '13 02:06

Prasad Kharkar


People also ask

What is the disadvantage of garbage collection in Java?

Drawbacks of garbage collection in Java Garbage collectors bring some runtime overhead that is out of the programmer's control. This could lead to performance problems for large applications that scale large numbers of threads or processors, or sockets that consume a large amount of memory.

How garbage collection makes Java more memory efficient?

Garbage collection makes Java memory efficient because it removes the unreferenced objects from heap memory and makes free space for new objects. The Java Virtual Machine has eight types of garbage collectors.

Does garbage collection affect performance Java?

The most common performance problem associated with Java™ relates to the garbage collection mechanism. If the size of the Java heap is too large, the heap must reside outside main memory. This causes increased paging activity, which affects Java performance.

What will happen when garbage collection kicks off in Java?

7. What happens to the thread when garbage collection kicks off? Explanation: The thread is paused when garbage collection runs which slows the application performance.


1 Answers

An OutOfMemoryError can occur if none of the objects in memory is eligible for garbage collection. For example:

List<MyClass> hellos = new ArrayList<>();
for (;;) {
   hellos.add(new MyClass());
}

This creates a list and keeps adding MyClass objects to it until memory runs out. None of the objects is eligible for garbage collection because there are references to all of them.

like image 110
Code-Apprentice Avatar answered Sep 19 '22 21:09

Code-Apprentice