Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does memory allocation of an ArrayList work?

As far as I know, when we are creating an ArrayList:

ArrayList<String> list = new ArrayList<String>(SIZE); 

The JVM reserves for it a contiguous part of memory. When we are adding new elements into our list, when number of elements reaches 75% of SIZE it reserves a new, contiguous part of memory and copies all of the elements.

Our list is getting bigger and bigger. We are adding new objects and the list has to be rebuilt once again.

What happens now?

The JVM is looking for a contiguous segment of memory, but it does not find enough space.

The Garbage Collector can try to remove some unused references and defragment memory. What happens, if the JVM is not able to reserve space for new instance of list after this process?

Does it create a new one, using maximal possible segment? Which Exception will be thrown?

I read this question Java: How ArrayList manages memory and one of the answers is:

Reference doesn't consume much space. but anyhow, some of space is used. When array is getting bigger, it could be a problem. We cannot also forget that we have got another things which use memory space.

like image 982
ruhungry Avatar asked Apr 23 '14 13:04

ruhungry


People also ask

Does ArrayList have contiguous memory allocation?

ArrayLists use contiguous memory. All elements in the ArrayList are located next to each other in the same memory space.

What happens if you add an element to an ArrayList when its memory allocation is reached?

ArrayList<String> list = new ArrayList<String>(SIZE); The JVM reserves for it a contiguous part of memory. When we are adding new elements into our list, when number of elements reaches 75% of SIZE it reserves a new, contiguous part of memory and copies all of the elements. Our list is getting bigger and bigger.

How does memory allocation work in Java?

In Java, memory management is the process of allocation and de-allocation of objects, called Memory management. Java does memory management automatically. Java uses an automatic memory management system called a garbage collector. Thus, we are not required to implement memory management logic in our application.


1 Answers

If JVM is not able to allocate requested amount of memory it'll throw

OutOfMemoryError 

That's it. Actually JVM memory allocation has only two possible outcomes:

  1. Application is given requested amount of memory.
  2. JVM throws OutOfMemoryError.

There is no intermediate options, like some amount of memory is allocated.

It has nothing to do with ArrayList, it's a JVM issue. If you asking whether ArrayList somehow manages this situation in a special way - then answer is "No, it does not." It just tries to allocate amount of memory it needs and lets JVM think about the rest.

like image 170
Denis Kulagin Avatar answered Sep 26 '22 04:09

Denis Kulagin