Java中的Integer()有多大? [英] How big is an Integer() in Java?

查看:2147
本文介绍了Java中的Integer()有多大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整数()有多大?我问下面是发生了什么。

Just how big is an Integer()? I ask because of what happened below.

在尝试将10 ^ 6个整数(在[0,10 ^ 6)中)放入双精度后,我的堆内存耗尽了 - 队列。该实现使用双向链表并显示为

I ran out of heap memory after trying to put 10^6 integers (in [0, 10^6) ) into a double-ended queue. The implementation uses a doubly-linked list and appears as

Deque<Item> implements Iterable<Item> { }

但是当使用Strings时,我能够完成而无需增加堆的大小:

But when using Strings, I was able to finish without having to increase the size of the heap:

String hw = "Hello, world."; 

for (i=0;i<10**6;i++) {
 myDq.addToEnd(hw); 
}


推荐答案

hw 总是引用相同的一个对象,所以即使你要添加10 ^ 6项(因此内部有~10 ^ 6个节点),你只需要一个字符串已分配对象 - 许多对该对象的引用,但只有一个对象。

hw always references the same one object, so even though you're adding 10^6 items (and thus have ~10^6 nodes internally), you'll only have one String object allocated -- lots of references to that one object, but just that one object.

事实上,即使你做了类似的事情:

In fact, even if you did something like:

for (i=0;i<10**6;i++) {
  String hs = "Hello, world."
  myDq.addToEnd(hw); 
}

你只有一个字符串因为字符串实习:整个JVM中所有相等的字符串文字都使用相同的 String object。

You'd only have one String because of string interning: all equal string literals across the whole JVM use the same one String object.

我怀疑如果你把它改成一点,你会得到相同的OOM:

I suspect you'll get the same OOM if you change it a bit to:

for (i=0;i<10**6;i++) {
  String hs = new String("Hello, world.".toCharArray());
  myDq.addToEnd(hw); 
}

分配新的字符串每次都带有原始 String 的char数组的副本。

That allocates a new String each time, with a copy of the original String's char array.

(OOM是常见的 OutOfMemoryError 的昵称,这是Java在堆空间用尽时抛出的东西,并且无法通过垃圾收集器(GC)回收。在这种情况下,列表和所有可通过它访问的对象 - 内部节点对象, 整数字符串值等 - 程序仍然可以达到,因此无法进行GC ,因此JVM无处可寻求更多的堆空间。)

(OOM is a common nickname for OutOfMemoryError, which is what Java throws when it's run out of heap space and can't reclaim enough through the garbage collector (GC). In this case, the list and all the objects reachable through it -- the internal node objects, the Integer or String values, etc -- can still be reached by the program and thus can't be GC'ed, so the JVM has nowhere to turn to for more heap space.)

这篇关于Java中的Integer()有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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