{"record":{"id":"26a018cc2e207db6","repo":"google/gson","slug":"cannot-allocate-c-usage-of-jdk-sun-misc-unsafe","errorCode":null,"errorMessage":"Cannot allocate ${c}. Usage of JDK sun.misc.Unsafe is enabled, but it could not be used. Make sure your runtime is configured correctly.","messagePattern":"Cannot allocate (.+?)\\. Usage of JDK sun\\.misc\\.Unsafe is enabled, but it could not be used\\. Make sure your runtime is configured correctly\\.","errorType":"exception","errorClass":"UnsupportedOperationException","httpStatus":null,"severity":"critical","filePath":"gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java","lineNumber":121,"sourceCode":"          ObjectInputStream.class.getDeclaredMethod(\"newInstance\", Class.class, Class.class);\n      newInstance.setAccessible(true);\n      return new UnsafeAllocator() {\n        @Override\n        @SuppressWarnings(\"unchecked\")\n        public <T> T newInstance(Class<T> c) throws Exception {\n          assertInstantiable(c);\n          return (T) newInstance.invoke(null, c, Object.class);\n        }\n      };\n    } catch (Exception ignored) {\n      // OK: try the next way\n    }\n\n    // give up\n    return new UnsafeAllocator() {\n      @Override\n      public <T> T newInstance(Class<T> c) {\n        throw new UnsupportedOperationException(\n            \"Cannot allocate \"\n                + c\n                + \". Usage of JDK sun.misc.Unsafe is enabled, but it could not be used.\"\n                + \" Make sure your runtime is configured correctly.\");\n      }\n    };\n  }\n}\n","sourceCodeStart":103,"sourceCodeEnd":130,"githubUrl":"https://github.com/google/gson/blob/310ac341f2f92a454b229bf21f70d2d18b2b6db7/gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java#L103-L130","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Add an accessible no-arg constructor to the target class (preferred).","Register a com.google.gson.InstanceCreator<T> via GsonBuilder.registerTypeAdapter to construct the instance yourself.","Open the package/module to Gson with --add-opens java.base/sun.misc=ALL-UNNAMED if the runtime still ships Unsafe.","Switch to a runtime/JVM that exposes sun.misc.Unsafe, or upgrade Gson (newer versions reduce reliance on Unsafe)."],"exampleFix":"// before: no constructor and Unsafe disabled -> UnsupportedOperationException\nclass Money(val cents: Long)\n\n// after: add no-arg constructor or register an InstanceCreator\nclass Money(val cents: Long = 0L)\n\n// alternative: explicit InstanceCreator\nGsonBuilder().registerTypeAdapter(Money::class.java, InstanceCreator<Money> { Money(0) }).create()","handlingStrategy":"fallback","validationCode":"// Provide an InstanceCreator so Unsafe is never consulted\nclass MoneyCreator implements InstanceCreator<Money> {\n  public Money createInstance(Type t) { return new Money(0L); }\n}\nGson gson = new GsonBuilder().registerTypeAdapter(Money.class, new MoneyCreator()).create();\n// Or ensure a no-arg constructor exists\nstatic boolean hasNoArgCtor(Class<?> c) {\n  try { c.getDeclaredConstructor(); return true; }\n  catch (NoSuchMethodException e) { return false; }\n}","typeGuard":"static boolean isUnsafeAllocatable(Class<?> c) {\n  try { return sun.misc.Unsafe.class.getMethod(\"allocateInstance\", Class.class) != null; }\n  catch (Exception e) { return false; }\n}","tryCatchPattern":"try {\n  gson.fromJson(json, Money.class);\n} catch (UnsupportedOperationException e) {\n  if (e.getMessage().contains(\"sun.misc.Unsafe\")) {\n    // register InstanceCreator or add ctor, then retry\n    log.warn(\"Unsafe unavailable for {}; provide InstanceCreator\", Money.class);\n  }\n  throw e;\n}","preventionTips":["Always add an accessible no-arg constructor to types Gson must deserialize.","Register InstanceCreator for classes you cannot modify.","On JDK 17+, add required --add-opens flags or migrate off Unsafe-dependent instantiation.","Test deserialization on the production runtime early (GraalVM, restricted JVMs)."],"tags":["reflection","unsafe","instantiation","jdk-version","deserialization","android"],"backgroundTag":null,"analyzedSha":"310ac341f2f92a454b229bf21f70d2d18b2b6db7","analyzedAt":"2026-08-10T02:58:47.455Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}