Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to get address on heap of a variable in java?

lets say i have this variable :

...
Somekindofobject var = new Somekindofobject();
...

and i want to know where var is located on the heap ( by address , like 0x08 and so on),and to print the address out .

is it possible?

like image 871
RanZilber Avatar asked Jan 10 '11 20:01

RanZilber


People also ask

Can we print address of variable in Java?

It is impossible to get an address of any primitive variable or object in Java. All that you can do is get default object hash code (which usually related to its address, but it is not guaranteed) with System. identityHashCode(a) .

Can you access memory address in Java?

@Peter Lawrey: Yes, you can access memory relative to an object (to read instance fields) or access memory at an absolute location. Objects get moved around in memory, so the address of an object has limited meaning.

Can we access heap memory in Java?

Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory. These objects have global access and we can access them from anywhere in the application.

Are addresses stored on stack or heap?

Stack is stores only primitive data types and addresses pointing to objects stored on Heap(object references). And all variables created on Stack are local and exists only while function executes, this concepts is called "variable scope"(local and global variables).


2 Answers

i am working on a program that gets as input java program , and instruments code that prints out to file information about variable access. The only way that i can determine between two fields of objects of the same class is by thier address on heap. Therefore, i need the address on heap

You can use System.identityHashCode to get a notion of sameness. It's not perfect, but it's pretty good. If you do get the heap address of an object, remember that the JVM is allowed to move objects around (and frequently does when a generational garbage collector promotes a long lived object to an older generation) so the heap location of an object is not a good proxy for identity in all circumstances.

like image 183
Mike Samuel Avatar answered Oct 20 '22 18:10

Mike Samuel


You might give a try on this article of javaPaper: Address of a Java object

It's about using the Unsafe class in the sun.misc package to get the address.

like image 26
jhurtado Avatar answered Oct 20 '22 18:10

jhurtado