开发者

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 .

i开发者_开发技巧s it possible?


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.


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.


Even if you managed to get the heap address of the object there is no guarantee that by the time you've used it the object is still there. The garbage collector may move the object to another location at any time. Unlike .NET java does not support memory pinning. If you are look to push data into an address from native code a DirectByteBuffer might be what you need.


Aside mentioned Unsafe which is well... useful (I have used it myself in a production environment). There is another solution which will not return the Java address as native pointer it's called direct java.nio.ByteBuffer, it has been designed with exactly that idea in mind. It allocated memory by direct ByteBuffer is not allocated in the java heap and it's not subject of standard garbage collection. Then, of course, ByteBuffer offers the direct pointer via ByteBuffer.address()


Given your goals, I think that the only solution is JVMTI. You would associate a unique identifier with each object using the {SetTag} operation. Then listen for {FieldModification} events.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜