How to access memory location in Java?

后端 未结 4 1135
天涯浪人
天涯浪人 2021-01-14 18:32

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 indire

相关标签:
4条回答
  • 2021-01-14 19:03

    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

    0 讨论(0)
  • 2021-01-14 19:07

    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?

    0 讨论(0)
  • 2021-01-14 19:07

    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 讨论(0)
  • 2021-01-14 19:14

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

    No.

    0 讨论(0)
提交回复
热议问题