Video in progress

Senior ☕ Core Java

People say reflection is slow. How do MethodHandle and VarHandle solve this problem?

Method.invoke does checks and wraps the arguments in an array on every call. If a MethodHandle is looked up once and stored in a static final field, the JIT can inline it down to the level of an ordinary call. VarHandle gives atomic access to fields with memory ordering.

📖 Answer

Reflection's cost is in three places:

  1. Lookup: getDeclaredMethod and getDeclaredFields return a copy every time. Not caching them is the most common mistake.
  2. Checks: the access check, wrapping the arguments in an Object[], boxing primitives.
  3. No inlining: for the JIT, the target inside invoke is unknown.

Starting with JDK 18, core reflection was rewritten to use MethodHandle internally (JEP 416), so the difference isn't as big as in older versions. But the fastest path is still:

final class Accessors {
    private static final MethodHandle GET_NAME;
    static {
        try {
            GET_NAME = MethodHandles.lookup()
                .findVirtual(User.class, "getName", MethodType.methodType(String.class));
        } catch (ReflectiveOperationException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    static String name(User u) throws Throwable {
        return (String) GET_NAME.invokeExact(u); // the types must match exactly
    }
}

static final is important: the JIT treats the handle as a constant and inlines the call.

VarHandle is the official replacement for sun.misc.Unsafe and AtomicXxxFieldUpdater: operations like compareAndSet, getAcquire and setRelease directly on a field.

When to use what:

  • a one-time job (reading configuration, startup): plain reflection is enough;
  • a hot path (a serializer, a mapper, on every request): MethodHandle or code generation (an annotation processor, MapStruct);
  • a lock-free structure: VarHandle.

Don't decide without measuring: write a JMH benchmark, because the JIT changes the result a lot.