开发者

How to access memory location in Java?

开发者 https://www.devze.com 2022-12-28 19:08 出处:网络
Is it possible开发者_如何学运维 that we can access memory location in Java directly or indirectly?

Is it possible开发者_如何学运维 that we can access memory location in Java directly or indirectly?

If we tries to print a object, it will print hashcode. Does hashcode signify indirectly to memory location?

For two object at different memory location but still their hashcode can varies.

-Abhishek


Is it possible that we can access memory location in Java directly or indirectly?

No.


No, hashcode, in general, has nothing to do with memory location. The memory location of your object is the object's reference itself.

However, it may not be quite impossible to squeeze out the actual location. Java Object's hashcode is, according to its javadoc, typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language. And there's System#identityHashCode(Object)method, which will return the same hash code for the given object as would be returned by the default method hashCode() (that is, Object's hashCode()). So this way you may indeed be able to get the actual memory location. But whether this works is, as said above, implementation dependent. And since you definitely won't be able to directly read/write in the memory even though you knew the location, what would you do with that information?


Probably not for a primitive data type. You might be able to get addresses of data areas used for object storage on a reference type, though Java Native Interface, we can access the C++ or C and from that we can get the Memory location.

It's sort of pointless, though. Because of garbage collection, any Java object can get moved in memory any time that any thread creates a new object


You can read/write memory addresses if some API is provided to do it. On the Sun/Oracle JRE sun.misc.Unsafe allows you to do this, although intentionally you have to go through hoops to get hold of an instance.

0

精彩评论

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

关注公众号