ruhungry ruhungry - 1 year ago 298
Java Question

How does memory allocation of an ArrayList work?

As far as I know, when we are creating an


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
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
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.

Answer Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download