Sunday, April 17, 2011

Address of a Java Object

Java has no pointers, but still there are methods which let us know address of objects.
Unsafe is a class that belongs to sun.misc package, to which may be you are new.

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. 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. But lets see.

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!
The program had following steps:

  • 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);
 }
}

No comments:

Post a Comment

Chitika