Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

Your platform's internal high-performance libraries still use sun.misc.Unsafe for field CAS and off-heap memory. Recent JDKs warn about Unsafe memory access methods and plan to remove them. How do you plan the migration?

We plan it as an inventory followed by two separate migrations. First we find every use of sun.misc.Unsafe, in our code and in dependencies, and classify each as field or array access or as off-heap memory. Field and array atomics move to VarHandle, which offers the same orderings through a supported API, and off-heap allocation moves to the Foreign Function and Memory API, MemorySegment and Arena. Because performance was the reason for Unsafe, every change is benchmarked with JMH, and the JDK's Unsafe memory access option is used to find what remains.

Background to this question

sun.misc.Unsafe has been the hidden engine of high-performance Java for twenty years. It was never a supported API, but libraries used it because nothing else was as fast. Now the JDK has supported replacements, and it has started the process of removing Unsafe's memory access methods: deprecating them for removal, then warning at run time, with denial and removal planned later. A platform team that ignores this will meet it as a sudden failure on some future JDK. In this answer, we will recap why Unsafe is being retired, build the inventory, migrate field operations to VarHandle and off-heap memory to the FFM API, benchmark, and use the JDK's own warnings to find the remaining uses.

1A Quick Recap: Why Unsafe Is Being Retired

sun.misc.Unsafe lets code read and write memory at raw addresses and offsets, allocate memory outside the heap, and perform CAS on any field given its offset. Nothing is checked. A wrong offset or a freed address does not throw an exception; it reads garbage, corrupts another object, or crashes the JVM. That is a problem for the integrity of the whole platform, and it also blocks JVM optimisations, because the JVM cannot assume anything about memory that Unsafe can change behind its back.

Since Java 9, VarHandle covers field and array access, and since Java 22 the Foreign Function and Memory API is final and covers off-heap memory. With replacements in place, JEP 471 in JDK 23 deprecated Unsafe's memory access methods for removal, and JEP 498 in JDK 24 made the JVM print a warning the first time one is used. The plan is to deny them by default in a later release and then remove them. The exact defaults change per release, so check your JDK version.

2Build the Inventory

We cannot plan what we have not counted. In our own code a search for sun.misc.Unsafe finds the class that obtains the instance, usually through reflection on its theUnsafe field, and then every call through it. For dependencies a search is not enough, because the calls are inside jars, so we use the JVM itself: running the test suite with the Unsafe memory access option in debug mode prints a stack trace for each use, which tells us which library made it.

Java
# our own code
grep -rn "sun.misc.Unsafe" --include=*.java src/ | wc -l
# 37
# our code and every dependency, as seen by the JVM (JDK 23 and later; check your version)
java --sun-misc-unsafe-memory-access=debug -jar service.jar
# WARNING: A terminally deprecated method in sun.misc.Unsafe has been called
# WARNING: sun.misc.Unsafe::allocateMemory has been called by com.acme.buffers.OffHeapPool
# ...stack trace...
Unsafe operations and their supported replacements
Unsafe useReplacementNotes
objectFieldOffset + compareAndSwapIntVarHandle compareAndSetfindVarHandle on the field
getLongVolatile / putOrderedLonggetVolatile / setReleasesame orderings, typed
array element CASarrayElementVarHandlebounds checked
allocateMemory / freeMemoryArena.allocate / arena closelifetime is explicit
getLong / putLong on an addressMemorySegment.get / setbounds and liveness checked
copyMemoryMemorySegment.copyworks across heap and off-heap
loadFence / storeFence / fullFenceVarHandle.acquireFence etc.static methods

Then we classify each use, because the two kinds have different replacements and different risks. Field and array access covers objectFieldOffset with compareAndSwapInt, getLongVolatile, putOrderedLong and the like. Off-heap memory covers allocateMemory, freeMemory, getLong and putLong on raw addresses, copyMemory and setMemory. A third small group, such as fences, maps directly to static VarHandle methods.

3Field and Array Atomics to VarHandle

This migration is mechanical and low risk. Each offset becomes a VarHandle created once, and each Unsafe call becomes the access mode with the same ordering.

Java
// before
private static final Unsafe U = UnsafeAccess.get();
private static final long STATE = U.objectFieldOffset(Node.class.getDeclaredField("state"));
boolean claim() { return U.compareAndSwapInt(this, STATE, 0, 1); }
void publish(long seq) { U.putOrderedLong(this, SEQ, seq); }
// after
private static final VarHandle STATE_H;
private static final VarHandle SEQ_H;
static {
try {
var l = MethodHandles.lookup();
STATE_H = l.findVarHandle(Node.class, "state", int.class);
SEQ_H = l.findVarHandle(Node.class, "seq", long.class);
} catch (ReflectiveOperationException e) { throw new ExceptionInInitializerError(e); }
}
boolean claim() { return STATE_H.compareAndSet(this, 0, 1); } // true for the first caller only
void publish(long seq) { SEQ_H.setRelease(this, seq); } // putOrdered was release semantics

Notice the ordering mapping: putOrderedLong was a release store, so it becomes setRelease, not setVolatile, which would be correct but slower. Getting these mappings right is where a review by someone who knows the memory model pays off.

4Off-Heap Memory to the FFM API

Off-heap code needs a real redesign of lifetimes, not just a rename. With Unsafe, a long address is just a number, and nothing stops us from using it after freeMemory. In the FFM API, memory lives in a MemorySegment, which knows its size, and every segment belongs to an Arena, which decides when the memory is freed.

Java
// before
long addr = U.allocateMemory(1024);
U.putLong(addr + 8, 42L);
long v = U.getLong(addr + 8); // 42
U.freeMemory(addr);
U.getLong(addr + 8); // undefined: garbage or a JVM crash
// after
try (Arena arena = Arena.ofConfined()) { // one owner thread; ofShared() for many
MemorySegment seg = arena.allocate(1024);
seg.set(ValueLayout.JAVA_LONG, 8, 42L);
long w = seg.get(ValueLayout.JAVA_LONG, 8); // 42
seg.get(ValueLayout.JAVA_LONG, 1024); // IndexOutOfBoundsException, not a crash
} // memory freed here
// any later access to seg throws IllegalStateException

So the class of bugs that crashes JVMs becomes ordinary exceptions. The design question is choosing the arena for each pool: a confined arena for memory used by one thread, a shared arena for memory handed between threads, and Arena.ofAuto() when the garbage collector should decide. Long-lived pools typically use one shared arena per pool, closed when the pool shuts down.

5Benchmark Every Change With JMH

Unsafe was chosen for speed, so a migration that is correct but slower will be rejected by the teams that depend on it. We write JMH benchmarks, the JDK project's microbenchmark harness that handles warm-up and dead-code elimination for us, for each hot path before changing it, then compare after. VarHandles in static final fields usually compile to the same instructions as Unsafe. MemorySegment access adds bounds and liveness checks, which the JIT often removes in loops but not always, so off-heap hot loops deserve the closest look.

We keep the benchmarks in the repository and run them on each new JDK, because the JIT keeps improving, and a gap we see today may close in the next release.

6Use the JDK's Switch to Track Progress

The --sun-misc-unsafe-memory-access option is our progress meter. In CI we run the test suites with it set to warn or debug and collect the warnings by caller, so the dashboard shows remaining uses per service and per library. Once a service is clean, we run its tests with the option set to deny, which makes any Unsafe memory access throw, so a dependency upgrade that brings Unsafe back fails the build instead of reaching production.

Step throughMigration plan for the platform
  1. Inventory with grep and the debug optionour code and dependencies
  2. Classify each usefield or array access, or off-heap memory
  3. Fields and arrays to VarHandlemechanical, review the orderings
  4. Off-heap to MemorySegment and Arenaredesign lifetimes
  5. JMH shows a regression?
    YesTune or keep the old path behind a flagNoShip the change
  6. Run CI with deny once cleanstops Unsafe coming back

6 steps in order. Play them, or step through them one at a time.

7Follow-up questions

Which third-party libraries in a typical Spring service still touch Unsafe?

The usual ones are networking and serialisation libraries: Netty for its buffers, protobuf-java for fast field access, compression libraries such as LZ4, some serialisers such as Kryo, and parts of Guava and older caching libraries. Many have already moved to VarHandle and the FFM API or fall back automatically when Unsafe is unavailable, so the first step is upgrading them and checking their release notes; the debug run then shows which ones still call it in our version.

Can we just keep Unsafe and add the allow option?

For a while, yes: setting the option to allow silences the warnings on releases where it is accepted. But it only buys time, because later releases are planned to deny and then remove these methods. Using the option as a temporary, tracked exception is fine; using it as the plan is not.

8Conclusion

In this answer, we planned the move away from sun.misc.Unsafe in steps. We built an inventory with a source search and the JDK's Unsafe memory access option in debug mode, classified each use as field or array access or off-heap memory, replaced field and array atomics with VarHandle using the same orderings, and redesigned off-heap code around MemorySegment and Arena. We benchmarked each change with JMH, and used the same option in CI to track the remaining uses and finally deny them.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd treat it as an inventory plus two different migrations. First, the inventory: grep our code for sun.misc.Unsafe, and run the test suites with --sun-misc-unsafe-memory-access=debug, which on recent JDKs prints a stack trace for each use, so I also find the calls inside dependencies.

Then, if they want more

Then classify each use. Field and array operations, like objectFieldOffset with compareAndSwapInt or putOrderedLong, move to VarHandle: findVarHandle once into a static final field, then compareAndSet, getVolatile or setRelease with the same ordering, which is mostly mechanical but needs a memory-model review.

Off-heap memory, allocateMemory, getLong, putLong, copyMemory, moves to the Foreign Function and Memory API: MemorySegments allocated from an Arena, where the arena decides the lifetime. That's more of a redesign, but it turns use-after-free and out-of-bounds bugs into exceptions instead of JVM crashes.

Since performance is the reason Unsafe was used, I'd write JMH benchmarks for each hot path before and after, and keep them to rerun on new JDKs. For dependencies, I'd upgrade first, since Netty, protobuf and others are migrating.

Finally I'd use the same JVM option in CI as a meter: warn to collect remaining uses per service, then deny once a service is clean, so Unsafe can't creep back in. The exact defaults differ by JDK version, so I'd check them for ours.

About this answer

Last updated
12 November 2026
Versions it names
Java 23, Java 22, Java 24, Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your platform's internal high-performance libraries still use sun.misc.Unsafe for field...": https://scrivio-interview-library.netlify.app/java/reflection-and-method-handles/1c4a028ed6/