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

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

问题描述

据我所知,当我们创建一个ArrayList时:

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

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

JVM 为其保留内存的连续部分.当我们向列表中添加新元素时,当元素数量达到 SIZE 的 75% 时,它会保留一个新的、连续的内存部分并复制所有元素.

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.

现在发生了什么?

JVM 正在寻找一段连续的内存,但找不到足够的空间.

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

垃圾收集器可以尝试删除一些未使用的引用并对内存进行碎片整理.如果在此过程之后 JVM 无法为列表的新实例保留空间,会发生什么情况?

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?

它是否使用最大可能的细分创建了一个新细分?哪个Exception会被抛出?

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

我阅读了这个问题Java:ArrayList 如何管理内存,其中一个答案是:

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.

推荐答案

如果 JVM 无法分配请求的内存量,它将抛出

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

OutOfMemoryError

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

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

  1. 应用程序获得请求的内存量.
  2. JVM 抛出 OutOfMemoryError.

没有中间选项,比如分配了一些内存.

它与 ArrayList 无关,这是一个 JVM 问题.如果您问 ArrayList 是否以某种特殊方式管理这种情况 - 那么答案是不,它没有".它只是尝试分配它需要的内存量,让 JVM 考虑其余的.

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天全站免登陆