如何一个ArrayList的内存分配工作? [英] How does memory allocation of an ArrayList work?

查看:401
本文介绍了如何一个ArrayList的内存分配工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,我们正在创建一个的ArrayList

 的ArrayList<串GT;名单=新的ArrayList<串GT;(大小);

在JVM储量它内存的连续一部分。当我们添加新元素到我们的列表中,当元素的数量达到75%尺寸它保留内存和副本的所有元素的一个新的,连续的一部分。

我们的名单越来越大。我们正在增加新的对象和列表,必须再次重建。

现在会发生什么事?

JVM的正在寻找一个连续的内存段,但它没有找到足够的空间。

垃圾收集器尝试删除一些不用的参考和整理内存。会发生什么,如果JVM是不能够在这个过程之后保留对清单的新实例的空间?

是否创建一个新的,使用最大可能细分?其中例外将被抛出?

我看了这个问题,的Java:ArrayList中如何管理内存和答案之一是:


  

参考不占用太多的空间。但无论如何,一些空间的使用。当数组越来越大,这可能是一个问题。我们不能也算了,我们已经得到了另一个东西使用的内存空间。



解决方案

如果JVM无法分配它会扔的内存要求金额

 的OutOfMemoryError

就是这样。其实JVM内存分配只有两种可能的结果:


  1. 应用程序给出的内存要求的数额。

  2. JVM抛出的OutOfMemoryError。

有没有中间选项,比如的内存量的分配。

它无关的的ArrayList 的,这是一个JVM的问题。如果你询问是否的ArrayList 的还是设法以一种特殊的方式这种情况 - 那么答案是没有,没有。它只是尝试分配它需要的内存量,并让JVM想想其余部分。

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.

解决方案

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.

这篇关于如何一个ArrayList的内存分配工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆