{"id":"529dbce1d450fc94","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":"error","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/8b8628c65699bc4421696183c62ae0c1b9b281dc/gson/src/main/java/com/google/gson/internal/UnsafeAllocator.java#L103-L130","documentation":"Thrown by the final fallback UnsafeAllocator when none of the allocation strategies (sun.misc.Unsafe.allocateInstance, Dalvik ObjectStreamClass.getConstructorId/newInstance, or pre-Gingerbread ObjectInputStream.newInstance) could be loaded. Gson uses these to instantiate classes that have no no-arg constructor without invoking any constructor; when all strategies fail the allocator becomes a stub that throws UnsupportedOperationException for every allocation. The {c} is the Class Gson tried to allocate.","triggerScenarios":"Deserializing a class with no accessible no-arg constructor on a JVM where sun.misc.Unsafe is inaccessible (removed or blocked by JPMS, or a non-HotSpot JVM). Used by ConstructorConstructor when reflection-based construction falls back to unsafe allocation (which is the default unless GsonBuilder.disableJdkUnsafe() is set).","commonSituations":"Running on JDK 17+ without --add-opens java.base/java.util=ALL-UNNAMED (or the relevant package); GraalVM Native Image; J9 / Avian / embedded JVMs; Android ART historically. Common when deserializing java.util collections or third-party value types without no-arg ctors.","solutions":["Add the required --add-opens to the JVM launch (e.g. --add-opens java.base/java.util=ALL-UNNAMED) so sun.misc.Unsafe.allocateInstance is reachable.","Give the target class a no-arg constructor (can be private) so Gson's ConstructorConstructor uses ordinary reflection instead of Unsafe.","Register an InstanceCreator for the type so Gson never reaches the Unsafe fallback.","If you intentionally forbid Unsafe, call GsonBuilder.disableJdkUnsafe() so Gson fails fast with a clear message about a missing InstanceCreator instead of hitting this stub."],"exampleFix":"// before: no default ctor + Unsafe blocked by JPMS\nclass Money { final long cents; Money(long c){cents=c;} }\n// -> UnsupportedOperationException: Cannot allocate Money ...\n\n// after: add a no-arg ctor Gson can reflect\nclass Money {\n  long cents;\n  private Money() {}\n  Money(long c){cents=c;}\n}","handlingStrategy":"validation","validationCode":"// Verify Unsafe reachability at startup if you rely on unsafe allocation\ntry {\n  Class<?> u = Class.forName(\"sun.misc.Unsafe\");\n  Field f = u.getDeclaredField(\"theUnsafe'); f.setAccessible(true);\n  Object unsafe = f.get(null);\n  u.getMethod(\"allocateInstance\", Class.class).invoke(unsafe, Object.class);\n} catch (Throwable t) {\n  // Unsafe unavailable — every class Gson deserializes must have a no-arg ctor or InstanceCreator\n}","typeGuard":null,"tryCatchPattern":"try {\n  return gson.fromJson(json, Money.class);\n} catch (UnsupportedOperationException e) {\n  if (e.getMessage() != null && e.getMessage().startsWith(\"Cannot allocate \")) {\n    throw new ConfigurationException(\"No no-arg constructor or InstanceCreator for \" + type\n        + \" and sun.misc.Unsafe is blocked; add --add-opens or register an InstanceCreator\", e);\n  }\n  throw e;\n}","preventionTips":["Add --add-opens java.base/<pkg>=ALL-UNNAMED for JDK built-in collection types.","Give deserialized classes a no-arg constructor (private is fine).","Call GsonBuilder.disableJdkUnsafe() during development to surface missing ctors/InstanceCreators early.","Register InstanceCreator for types you cannot modify."],"tags":["reflection","unsafe","jpms","deserialization","runtime"],"analyzedSha":"8b8628c65699bc4421696183c62ae0c1b9b281dc","analyzedAt":"2026-08-04T19:12:22.202Z","schemaVersion":2}