java内存数据检索,Java:如何像在C ++中一样存储和检索内存地址

I come from a C++ background. In C++ I can store a memory adress which I just new'd in a global array and re-use it later. For example, say I have two classes X, Y and I create two objects x, y. The global array StoreAddresses[2] is defined as:

uint32_t StoreAddresses[2];

I write:

X * x = new X();

Y * y = new Y();

StoreAdresses[0] = (uint32t *) x; //for example, 0x12345678

StoreAdresses[1] = (uint32t *) y; //for example, 0x12345698

Anywhere in my program, I can retrieve the data written in memory by calling:

X * stored_x = (X*)StoreAdresses[0];

Y * stored_y = (Y*)StoreAdresses[1];

How can I accomplish that in Java?

Appreciate the help!

解决方案

You can do this in Java using Unsafe. However its a very bad idea. That is because address of an object can change at any time (by a GC) If you store the address like this an use it later it might not be valid any more and even crash your application. If the GC believes an object does not have a strong reference, it may clean up the object. When you try to reference the object again, it may not be in the JVM any more.

The size of an address can change depending on how you start the JVM. A 64-bit JVM usually uses 32-bit references (which might a surprise coming from C++) You can get this with Unsafe.ADDRESS_SIZE

I would only use Unsafe to see what the addresses are to see how the objects are laid out in your cache. (Which is not very useful as there is not much you can about it :( )

It is likely that what ever you are trying to can be done a better way. Can you give us more details?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值