Over a million developers have joined DZone.

When All Else Fails: Using “the Unsafe”

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

Sometimes you have to hack. You just have to. Don’t listen to XKCD. You don’t always regret hacking. On our blog, we’ve shown a couple of hacks before:

But we’ve just been scratching the surface. Our friends at ZeroTurnaround /RebelLabs have recently published an awesome article about how to use “the Unsafe”. The sun.misc.Unsafe class to directly access memory in Java. While the first page introduces us to the Unsafe object itself and how to access it through reflection …

public static Unsafe getUnsafe() {
    try {
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        return (Unsafe) f.get(null);
    } catch (Exception e) {
        /* ... */
    }
}

… subsequent sections nicely explain how to map “unsafe” memory access methods to addressing a Class in memory, of objects in memory …

// If you're daring, go manipulate the heap directly!
Object helperArray[] = new Object[1];
helperArray[0] = targetObject;
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
long addressOfObject = unsafe.getLong(helperArray, baseOffset);

However, don’t think it’s so easy. In order to manipulate the Java heap directly, you will need to understand a lot about the various fields and flags in class headers, and you’ll always need to remember to distinguish between 32-bit and 64-bit JVMs.

This particular article was written at RebelLabs by Serkan Özal whose Open Source profile indicates that he’s a real hacker and “the Unsafe” is his home away from home.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of Lukas Eder, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}