google/gson · critical · UnsupportedOperationException

Cannot allocate . Usage of JDK sun.misc.Unsafe is enabled…

Error message

Cannot allocate ${c}. Usage of JDK sun.misc.Unsafe is enabled, but it could not be used. Make sure your runtime is configured correctly.

What it means

UnsafeAllocator tries three strategies to allocate an instance without calling a constructor (sun.misc.Unsafe.allocateInstance, two Dalvik ObjectStream tricks). When all three fail it installs a fallback allocator that throws UnsupportedOperationException for every newInstance call. This means Gson cannot construct an object of the target type because no reflection-free allocation path exists on the runtime.

Solutions

  1. Add an accessible no-arg constructor to the target class (preferred).
  2. Register a com.google.gson.InstanceCreator<T> via GsonBuilder.registerTypeAdapter to construct the instance yourself.
  3. Open the package/module to Gson with --add-opens java.base/sun.misc=ALL-UNNAMED if the runtime still ships Unsafe.
  4. Switch to a runtime/JVM that exposes sun.misc.Unsafe, or upgrade Gson (newer versions reduce reliance on Unsafe).

Example fix

// before: no constructor and Unsafe disabled -> UnsupportedOperationException
class Money(val cents: Long)

// after: add no-arg constructor or register an InstanceCreator
class Money(val cents: Long = 0L)

// alternative: explicit InstanceCreator
GsonBuilder().registerTypeAdapter(Money::class.java, InstanceCreator<Money> { Money(0) }).create()
Defensive patterns

Strategy: fallback

Validate before calling

// Provide an InstanceCreator so Unsafe is never consulted
class MoneyCreator implements InstanceCreator<Money> {
  public Money createInstance(Type t) { return new Money(0L); }
}
Gson gson = new GsonBuilder().registerTypeAdapter(Money.class, new MoneyCreator()).create();
// Or ensure a no-arg constructor exists
static boolean hasNoArgCtor(Class<?> c) {
  try { c.getDeclaredConstructor(); return true; }
  catch (NoSuchMethodException e) { return false; }
}

Type guard

static boolean isUnsafeAllocatable(Class<?> c) {
  try { return sun.misc.Unsafe.class.getMethod("allocateInstance", Class.class) != null; }
  catch (Exception e) { return false; }
}

Try / catch

try {
  gson.fromJson(json, Money.class);
} catch (UnsupportedOperationException e) {
  if (e.getMessage().contains("sun.misc.Unsafe")) {
    // register InstanceCreator or add ctor, then retry
    log.warn("Unsafe unavailable for {}; provide InstanceCreator", Money.class);
  }
  throw e;
}

Prevention

When it happens

Trigger: Deserializing a type that has no no-arg constructor and no registered InstanceCreator, on a runtime where sun.misc.Unsafe is unavailable or blocked (project Jigsaw modules, JEP 411 strong-encapsulation, or a non-HotSpot JVM). The fallback allocator is invoked by ConstructorConstructor during deserialization.

Common situations: JDK 17+ with --illegal-access denied and sun.misc.Unsafe filtered; GraalVM native image; older Android runtimes with patched Dalvik; security-managed JVMs that forbid theUnsafe.

Related errors


AI-assisted analysis of google/gson@310ac341f2 (2026-08-10). Data as JSON: /api/errors/26a018cc2e207db6. Report an issue: GitHub.

Appendix: source

Thrown at gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java:121

          ObjectInputStream.class.getDeclaredMethod("newInstance", Class.class, Class.class);
      newInstance.setAccessible(true);
      return new UnsafeAllocator() {
        @Override
        @SuppressWarnings("unchecked")
        public <T> T newInstance(Class<T> c) throws Exception {
          assertInstantiable(c);
          return (T) newInstance.invoke(null, c, Object.class);
        }
      };
    } catch (Exception ignored) {
      // OK: try the next way
    }

    // give up
    return new UnsafeAllocator() {
      @Override
      public <T> T newInstance(Class<T> c) {
        throw new UnsupportedOperationException(
            "Cannot allocate "
                + c
                + ". Usage of JDK sun.misc.Unsafe is enabled, but it could not be used."
                + " Make sure your runtime is configured correctly.");
      }
    };
  }
}

View on GitHub (pinned to 310ac341f2)