Address of a Java Object

05/07/2010

In conventional java programming, you will never need address or location of a java object from memory. When you discuss about this in forums, the first question raised is why do you need to know the address of a java object? Its a valid question. But always, we reserve the right to experiment. Nothing is wrong in exploring uncharted areas.

I thought of experimenting using a little known class from sun package. Unsafe is a class that belongs to sun.misc package. For some of you the package might be new. You need not worry about it. If you have sun’s JDK then you have this class already.

When a class name is “Unsafe” in java, it calls for your attention immediately. Then I decided to dig deep into it and find what is unsafe about that class. Voila, it really opens up the pandora’s box. Its difficult to find the source of Unsafe. Get the source and look at the methods you will know what I am referring to.

Java’s security manager provides sufficient cover and ensures you don’t fiddle with memory that easily. As a first step, I thought of getting the memory location of a java object. Until the exploration, I too was 100% confident that it was not possible to find the location / address of an object in java.

Ads by Google

Sun’s Unsafe.java api documentation shows us an opportunity to get the address using the method objectFieldOffset. That method says, “Report the location of a given field in the storage allocation of its class“. It also says, “it is just a cookie which is passed to the unsafe heap memory accessors“. Whatsoever, I am able to get the storage memory location of an object from the storage allocation of its class.

You can argue that, what we have got is not the absolute physical memory address of an object. But we have got the logical memory address. The following program will be quite interesting for you!

As a first step, I have to get an object of Unsafe class. It is quite difficult as the constructor is private. There is a method named getUnsafe which returns the unsafe object. Java’s security manager asks you to make your java source code privileged. I used little bit of reflection and got an instance out. I know there are better ways to get the instance. But to bypass the security easily I chose the following.

Using Unsafe’s object just invoke objectFieldOffset and staticFieldOffset. The result is address / location of object in the storage allocation of its class.

Following example program runs well on JDK 1.6

import sun.misc.Unsafe;
import java.lang.reflect.Field;

public class ObjectLocation {

 private static int apple = 10;
 private int orange = 10;

 public static void main(String[] args) throws Exception {
  Unsafe unsafe = getUnsafeInstance();

  Field appleField = ObjectLocation.class.getDeclaredField("apple");
  System.out.println("Location of Apple: "
    + unsafe.staticFieldOffset(appleField));

  Field orangeField = ObjectLocation.class.getDeclaredField("orange");
  System.out.println("Location of Orange: "
    + unsafe.objectFieldOffset(orangeField));
 }

 private static Unsafe getUnsafeInstance() throws SecurityException,
   NoSuchFieldException, IllegalArgumentException,
   IllegalAccessException {
  Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
  theUnsafeInstance.setAccessible(true);
  return (Unsafe) theUnsafeInstance.get(Unsafe.class);
 }
}
This Core Java tutorial was posted on 05/07/2010.
Ads by Google

46 comments on “Address of a Java Object

  1. Thanks for sharing, keep going………

  2. great info..thanks keep on sharing…

  3. Hey thanks for posting this valuable info.

  4. Hi Nice Try..

    When try executing the given program getting the below error..

    Access restriction: The type Unsafe is not accessible due to restriction on required library C:\Program Files
    \Java\jre6\lib\rt.jar

  5. Great information…Please keep sharing more stuffs

  6. Your concets are really great.I became a fan of ur tutorial. Keep it up

  7. Really gud article.. its nice 2 read ur all articles.Keep it up !!!

  8. Hi !!

    Its good article.. Keep on growing…

    Best of luck !!!

  9. Pingback: Resurrecting sun.misc.Unsafe | Codethink

  10. Pingback: Resurrecting sun.misc.Unsafe | Codethink

  11. The output of the java program is not the address of the field(s) but the offset of the field in the object.

  12. Well you CAN get an object’s address in physical memory using JNI. I realize this is a relatively old post, but if you are still interested let me know!

  13. N. ZAZA I am interested in getting the physical address in JNI any tips?

  14. Hello Everybody,
    this is a great tutorial for me and i learn a lot from this .Today
    this question is asked to me in interview ……..

  15. Hi Nice Try..

    When try executing the given program getting the below error..

    Access restriction: The type Unsafe is not accessible due to restriction on required library C:\Program Files
    \Java\jre6\lib\rt.jar

    plz tell me what this mean basically

  16. Misleading. This only finds an offset within the class/object, not an actual location of anything in memory.

  17. Suppose we make a class in a java prog and when we initialize an object of that class in other class in same package and when i write code as
    Box b1=new box();
    System.out.println(b1);
    it gives us an o/p which seems as the address of that object.
    is it correct and if correct why ??

    • No, its not the address of the object. Its just a string representation of the object. Which consists of class name and the hash code in hexadecimal format.

      getClass().getName() + ‘@’ + Integer.toHexString(hashCode())

      (Source: JavaDocs)

  18. It’s good one but it is only offset of object address……..can you please provide the physical address…

  19. So surprised…Nice article Joe

    Thanks,
    Anu

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>