Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to store and retrieve memory address like in 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!

like image 571
goseib Avatar asked Jan 18 '23 23:01

goseib


2 Answers

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?

like image 139
Peter Lawrey Avatar answered Feb 02 '23 06:02

Peter Lawrey


What Peter said is correct. I would add that you need to start thinking in java terms, not in C++ terms.

It might help you to know that in Java X x = new X(); is almost entirely equivalent to what in C++ is X* x = new X();

like image 29
Mike Nakis Avatar answered Feb 02 '23 08:02

Mike Nakis