Java对象和数组的内存位置
我正在用Java编写一个数组支持的哈希表,其中键和值的类型都是Object;没有其他保证。
对我来说,代码方面最简单的方法是创建一个对象来保存它们:
public class Pair {
public Object key;
public Object value;
}
然后创建一个数组
public Pair[] storage = new Pair[8];
但是 jvm 如何在内存中处理它?也就是说,该数组实际上是:
- 指向位于其他位置的 Pair() 对象的指针数组,还是
- 包含实际数据?
编辑
由于对象稍后被实例化为 new Pair(),因此它们被随机放置在堆中。有什么好的方法可以确保它们在堆中是连续的吗?我需要对 sun.misc.unsafe 进行一些欺骗才能使其工作吗?
解释一下我的动机,如果我想尝试确保连续项位于同一内存页面中,有什么方法可以在 Java 中做到这一点吗?
I'm writing an array-backed hashtable in Java, where the type of key and value are Object; no other guarantee.
The easiest way for me code-wise is to create an object to hold them:
public class Pair {
public Object key;
public Object value;
}
And then create an array
public Pair[] storage = new Pair[8];
But how does the jvm treat that in memory? Which is to say, will the array actually:
- be an array of pointers to Pair() objects sitting elsewhere, or
- contain the actual data?
edit
Since the objects are instantiated later as new Pair(), they're randomly placed in the heap. Is there any good way to ensure they're sequential in the heap? Would I need to do some trickery with sun.misc.unsafe to make that work?
Explaining my motivation, if I want to try and ensure that sequential items are in the same page of memory, is there any way to do this in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该数组将是堆上的一个对象,其中包含指向 Pair 对象的指针,该对象也将位于堆上(但与数组本身分开)。
The array will be an object on the heap containing pointers to the Pair objects which will also be on the heap (but separate from the array itself).
不,存储数组将只包含指向堆上其他地方存在的实际 Pair 对象的指针。但是,请记住实例化 8 个 Pair 对象,并使数组的每个元素都指向这些对象。在您编写的代码后面需要有这样的内容:
只有这样,Pair 对象才会被创建并被存储数组正确引用。
No, the storage array will only contain pointers to the actual Pair objects existing somewhere else on the heap. Yet, remember to instantiate 8 Pair objects and make each element of the array point to these objects. You need to have something like this after the code that you have written:
Only then will the Pair objects be created and correctly referred to by the storage array.