Playing with Unsafe – Swapping Objects

In this post we shall how to replace the reference to an existing object using Unsafe use.

We are going to reuse the Pointer object from earlier post

The code looks like this

public void playWithReferences() throws NoSuchFieldException {
  LockTrick lock1 = new LockTrick(1);
  LockTrick lock2 = new LockTrick(2);

  long add2 = getObjectAddess(lock2);

  Pointer pointer = new Pointer();
  pointer.pointer = lock1;
  System.out.println("Pointer = "+pointer.pointer);
  unsafe.putLong(pointer, unsafe.objectFieldOffset(Pointer.class.getDeclaredField("pointer")), add2);
  System.out.println("Pointer after reset "+pointer.pointer);
}

LockTrick class just displays the id and shall be used in further posts.

We create two objects. Assign first one to Pointer class variable. We get the Object address of second object we want to replace and use the put() to replace the reference. This shall make the pointer point to lock2 reference. The object can be off-heap as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.