Skip to content

Optimize new Gson()#2864

Merged
eamonnmcmanus merged 2 commits intogoogle:mainfrom
MukjepScarlet:gson_default
Jan 28, 2026
Merged

Optimize new Gson()#2864
eamonnmcmanus merged 2 commits intogoogle:mainfrom
MukjepScarlet:gson_default

Conversation

@MukjepScarlet
Copy link
Copy Markdown
Contributor

@MukjepScarlet MukjepScarlet commented Jun 23, 2025

Optimizes new Gson()

closes #2863

Comment thread gson/src/main/java/com/google/gson/Gson.java Fixed
@eamonnmcmanus
Copy link
Copy Markdown
Member

I'm not really convinced here. It might have been better if this had been the API from the outset, but now we have 17 years of client code that uses new Gson(). So I think it would be very disruptive to deprecate that, and if we don't then we have two different ways of doing the same thing.

However, it's true that every invocation of new Gson() ends up doing quite a lot of work in order to construct an exactly equivalent list of factories every time. I believe we could improve that situation as follows:

  • Replace the package-private Gson constructor that has 21 parameters by a constructor that takes a GsonBuilder parameter.
  • Have a static final GsonBuilder that the public Gson() constructor passes to the new Gson(GsonBuilder).
  • Somehow cache the List<TypeAdapterFactory> corresponding to this builder, and reuse it when the new constructor sees that it is being called a second time from the Gson() constructor.

The last item is potentially controversial, since it does mean that some memory would end up being retained even when there are no active Gson instances.

Whether or not we do the last item, I think the first two would be worthwhile, if only because it would eliminate the duplication whereby the default value for every Gson property is specified in both the Gson() constructor and the GsonBuilder instance initializers.

@MukjepScarlet
Copy link
Copy Markdown
Contributor Author

MukjepScarlet commented Oct 29, 2025

I will drop Gson.DEFAULT and try to make the Default constructor share more contents.

Comment thread gson/src/main/java/com/google/gson/GsonBuilder.java Fixed
Comment thread gson/src/main/java/com/google/gson/GsonBuilder.java Fixed
@MukjepScarlet
Copy link
Copy Markdown
Contributor Author

I need help about Java 9 modules...

@Marcono1234
Copy link
Copy Markdown
Contributor

Marcono1234 commented Nov 7, 2025

I need help about Java 9 modules...

It looks like there is something wrong with how the adapters are looked up. It is trying to use the reflective adapter for types such as java.lang.Double.

I have made some changes to this code here and proposed them as MukjepScarlet#1; that also fixes the test failures. If you are fine with them, you can merge them and they will directly appear in this PR here then.

But @MukjepScarlet, could you please edit the title of this PR here (click the "Edit" button at the top right) and rename it to something like "Reduce overhead of default Gson instances" or similar? The current title ("add Gson.DEFAULT") is misleading because the PR is not actually doing this anymore.

@MukjepScarlet MukjepScarlet changed the title add Gson.DEFAULT Optimize new Gson() Nov 8, 2025
@MukjepScarlet MukjepScarlet marked this pull request as ready for review November 8, 2025 05:29
@Marcono1234
Copy link
Copy Markdown
Contributor

@eamonnmcmanus, what do you think about the current state of this PR?

@eamonnmcmanus
Copy link
Copy Markdown
Member

eamonnmcmanus commented Nov 12, 2025

@eamonnmcmanus, what do you think about the current state of this PR?

The outline looks correct, but I think there is a subtle change in behaviour. When I ran this against Google's internal tests, I saw failures that looked like this:

Error occurred during initialization of VM
java.lang.BootstrapMethodError: java.lang.IllegalStateException: getSystemClassLoader cannot be called during the system class loader instantiation
        at com.google.gson.internal.ConstructorConstructor.newMapConstructor(ConstructorConstructor.java:381)
        at com.google.gson.internal.ConstructorConstructor.newDefaultImplementationConstructor(ConstructorConstructor.java:328)
        at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:137)
        at com.google.gson.internal.bind.MapTypeAdapterFactory.create(MapTypeAdapterFactory.java:146)
        at com.google.gson.Gson.getAdapter(Gson.java:349)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:205)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:396)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:165)
        at com.google.gson.Gson.getAdapter(Gson.java:349)
        at com.google.gson.Gson.fromJson(Gson.java:1079)
        at com.google.gson.Gson.fromJson(Gson.java:981)
        at com.google.gson.Gson.fromJson(Gson.java:891)
        at com.google.gson.Gson.fromJson(Gson.java:828)
        at [... Google-internal stuff ...]
        at java.lang.reflect.Constructor.newInstanceWithCaller(java.base@25/Constructor.java:499]
        at java.lang.reflect.Constructor.newInstance(java.base@25/Constructor.java:483]
        at java.lang.ClassLoader.initSystemClassLoader(java.base@25/ClassLoader.java:1889]
        at java.lang.System.initPhase3(java.base@25/System.java:1993]
Caused by: java.lang.IllegalStateException: getSystemClassLoader cannot be called during the system class loader instantiation
        at java.lang.ClassLoader.getSystemClassLoader(java.base@25/ClassLoader.java:1849]
        at java.lang.invoke.MethodHandles$Lookup.canBeCached(java.base@25/MethodHandles.java:4022]
        at java.lang.invoke.MethodHandles$Lookup.linkMethodHandleConstant(java.base@25/MethodHandles.java:3999]
        at java.lang.invoke.MethodHandleNatives.linkMethodHandleConstant(java.base@25/MethodHandleNatives.java:603]
        at com.google.gson.internal.ConstructorConstructor.newMapConstructor(ConstructorConstructor.java:381)
        at com.google.gson.internal.ConstructorConstructor.newDefaultImplementationConstructor(ConstructorConstructor.java:328)
        at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:137)
        at com.google.gson.internal.bind.MapTypeAdapterFactory.create(MapTypeAdapterFactory.java:146)
        at com.google.gson.Gson.getAdapter(Gson.java:349)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:205)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:396)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:165)
        at com.google.gson.Gson.getAdapter(Gson.java:349)
        at com.google.gson.Gson.fromJson(Gson.java:1079)
        at com.google.gson.Gson.fromJson(Gson.java:981)
        at com.google.gson.Gson.fromJson(Gson.java:891)
        at com.google.gson.Gson.fromJson(Gson.java:828)
        at [... more Google-internal stuff ...]

I guess this code is running with -Djava.system.class.loader=something, but in any case it is clearly triggering a code path that was not triggered before. I haven't had time to investigate further.

@Marcono1234
Copy link
Copy Markdown
Contributor

This PR does change () -> new C() to C::new in ConstructorConstructor.java (which is not actually needed for this PR).

If you revert those ConstructorConstructor.java changes, do the tests pass then? Would be quite interesting though that lambda vs. method reference makes a difference.

@MukjepScarlet
Copy link
Copy Markdown
Contributor Author

I'm interesting about that too. If you think the change of ConstructorConstructor is not needed (or should be in another PR), I'll revert it here.

@MukjepScarlet
Copy link
Copy Markdown
Contributor Author

I think this is the reason because stuffs like TreeMap::new will access getSystemClassLoader, but in the test it's not ready. This might need further test.

@Marcono1234
Copy link
Copy Markdown
Contributor

Marcono1234 commented Nov 13, 2025

I think I am able to reproduce this locally:

  1. For testing (but don't include it in this PR), add gson/src/main/java/com/google/gson/SystemClassLoader.java with this content:
    package com.google.gson;
    
    import java.util.Map;
    import java.util.concurrent.atomic.AtomicReference;
    
    public class SystemClassLoader extends ClassLoader {
        private static final AtomicReference<Object> value = new AtomicReference<>();
    
        public SystemClassLoader(ClassLoader parent) {
            super(parent);
            Object object = new Gson().fromJson("{}", Map.class);
            value.set(object);
        }
    
        @SuppressWarnings("SystemOut")
        public static void main(String[] args) {
            System.out.println(value.get());
            System.out.println("done");
        }
    }
  2. Build the Gson JAR
    mvn clean package --projects gson "-Dmaven.test.skip"
    
  3. Run with the custom system class loader
    java -cp ./gson/target/gson-2.13.3-SNAPSHOT.jar "-Djava.system.class.loader=com.google.gson.SystemClassLoader" com.google.gson.SystemClassLoader
    

Fails with the same stack trace as above. Replacing the method references in ConstructorConstructor fixes it.
Though to be sure, would be good @eamonnmcmanus if you could double-check if that is indeed the same issue.

In that case maybe we could indeed replace the method references in ConstructorConstructor with lambdas again. Though this seems somewhat brittle and I am wondering if there are other not-yet discovered issues which could occur when using Gson from within a custom system class loader.

Interestingly this only seems to affect LinkedTreeMap::new, maybe because it is a reference to a non-JDK class?
You can reproduce this with this custom class loader (and same build / run steps as above):

public class SystemClassLoader extends ClassLoader {
    public SystemClassLoader(ClassLoader parent) {
        super(parent);
        List<Supplier<?>> unused = Arrays.asList(
            ArrayList::new,
            LinkedHashSet::new,
            TreeSet::new,
            ArrayDeque::new,
            // LinkedTreeMap::new,
            () -> new LinkedTreeMap<>(),
            LinkedHashMap::new,
            TreeMap::new,
            ConcurrentHashMap::new,
            ConcurrentSkipListMap::new
        );
    }

    @SuppressWarnings("SystemOut")
    public static void main(String[] args) {
        System.out.println("done");
    }
}

Edit: It seems the reason why this issue only occurs for ...

At least that is my understanding of it. But this also seems to highly depend on JDK and compiler implementation details. But given that usage of lambdas here worked before apparently, that seems to be a reasonable solution, albeit brittle. Though using Gson in general from within the constructor of a custom system class loader seems to be brittle.

Comment thread gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java Outdated
Copy link
Copy Markdown
Member

@eamonnmcmanus eamonnmcmanus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! This is basically what I had in mind. But it looks like there are a lot of changes in here that are not really related to the important change, which is eliminating duplication between Gson and GsonBuilder. Would it possible to make it so that that is the only thing that changes?

@Marcono1234
Copy link
Copy Markdown
Contributor

Marcono1234 commented Nov 22, 2025

But it looks like there are a lot of changes in here that are not really related to the important change

Sorry, might also have been my fault to some extent due to the changes I had proposed to @MukjepScarlet.
I guess the changes to EnumTypeAdapter.java and ConstructorConstructor.java are unrelated and could be done in a separate PR indeed.

The changes to SqlTypesSupport.java and LongSerializationPolicy.java are related and probably nice to have since they slightly simplify creation of the default factories, but maybe could be omitted / be performed in a subsequent PR?

The change to TypeAdapters.java is closely related:
These adapters and factories are currently created within Gson.java, but with these changes, GsonBuilder instead of Gson now creates the default so it would make sense to move those adapters and factories out of Gson.java either way, and TypeAdapters.java seems suitable?
But maybe that could be done in a predecessor PR then? So first move the adapters and adapter factories to TypeAdapters in one PR, and then base this PR here on it.

@eamonnmcmanus, is that what you had in mind?

And @MukjepScarlet what do you think about this? Do you think this is a reasonable way to split this PR, and would you be able to do that?

@MukjepScarlet
Copy link
Copy Markdown
Contributor Author

MukjepScarlet commented Nov 23, 2025

Splitting the PR is reasonable, as certain changes within it were deliberately intended to serve as separate prerequisite PR. I have no objection. @Marcono1234

Comment thread gson/src/main/java/com/google/gson/internal/bind/EnumTypeAdapter.java Outdated
Comment thread gson/src/main/java/com/google/gson/internal/bind/EnumTypeAdapter.java Outdated
@eamonnmcmanus
Copy link
Copy Markdown
Member

(I'm still looking for a PR that has no changes other than the ones needed to remove the duplication between Gson and GsonBuilder. Not that those other changes are necessarily bad, they just shouldn't be here.)

@Marcono1234
Copy link
Copy Markdown
Contributor

@eamonnmcmanus, most of the changes have been moved by @MukjepScarlet into #2951, which is kind of a prerequisite for this PR here now I think. If possible could you please have a look at that PR?

Once that is (hopefully) merged and this PR here is updated, the remaining changes here should be only1 about the improvements for the Gson default instance.

Footnotes

  1. @MukjepScarlet, the EnumTypeAdapter change here is still unrelated to the Gson default instance changes though. Maybe it would be best to omit it from this PR here?

Co-authored-by: Marcono1234 <Marcono1234@users.noreply.github.com>
@MukjepScarlet
Copy link
Copy Markdown
Contributor Author

@eamonnmcmanus I think this is ready for review now.

Copy link
Copy Markdown
Member

@eamonnmcmanus eamonnmcmanus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the long delay here. It looks like this PR is now focused on the one change of reducing duplication in Gson and GsonBuilder. I have one very minor comment, but it can potentially be addressed in a follow-up.


private static Gson createGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.excluder = CUSTOM_EXCLUDER;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be a bit cleaner to set these values through the public API of GsonBuilder.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, better readability, just like how we use it outside of this package.

@eamonnmcmanus eamonnmcmanus merged commit 8526dbd into google:main Jan 28, 2026
16 checks passed
@MukjepScarlet MukjepScarlet deleted the gson_default branch January 28, 2026 17:02
@eamonnmcmanus
Copy link
Copy Markdown
Member

Thanks again, @MukjepScarlet, for seeing this PR through to completion! I think it's a great simplification of the code.

mergify Bot added a commit to ArcadeData/arcadedb that referenced this pull request Apr 27, 2026
…ip ci]

Bumps [com.google.code.gson:gson](https://github.com/google/gson) from 2.13.2 to 2.14.0.
Release notes

*Sourced from [com.google.code.gson:gson's releases](https://github.com/google/gson/releases).*

> Gson 2.14.0
> -----------
>
> What's Changed
> --------------
>
> * Add type adapters for `java.time` classes by [`@​eamonnmcmanus`](https://github.com/eamonnmcmanus) in [google/gson#2948](https://redirect.github.com/google/gson/pull/2948)
>
>   When the `java.time` API is available, Gson automatically can read and write instances of classes like `Instant` and `Duration`. The format it uses essentially freezes the JSON representation that `ReflectiveTypeAdapterFactory` established by default, based on the private fields of `java.time` classes. That's not a great representation, but it is understandable. Changing it to anything else would break compatibility with systems that are expecting the current format.
>
>   With this change, Gson no longer tries to access private fields of these classes using reflection. So it is no longer necessary to run with `--add-opens` for these classes on recent JDKs.
> * Remove `com.google.gson.graph` by [`@​eamonnmcmanus`](https://github.com/eamonnmcmanus) in [google/gson#2990](https://redirect.github.com/google/gson/pull/2990).
>
>   This package was not part of any released artifact and depended on Gson internals in potentially problematic ways.
> * Validate that strings being parsed as integers consist of ASCII characters by [`@​eamonnmcmanus`](https://github.com/eamonnmcmanus) in [google/gson#2995](https://redirect.github.com/google/gson/pull/2995)
>
>   Previously, strings could contain non-ASCII Unicode digits and still be parsed as integers. That's inconsistent with how JSON numbers are treated.
> * Fix duplicate key detection when first value is null by [`@​andrewstellman`](https://github.com/andrewstellman) in [google/gson#3006](https://redirect.github.com/google/gson/pull/3006)
>
>   This could potentially break code that was relying on the incorrect behaviour. For example, this JSON string was previously accepted but will no longer be: `{"foo": null, "foo": bar}`.
> * Remove `Serializable` from internal `Type` implementation classes. by [`@​eamonnmcmanus`](https://github.com/eamonnmcmanus) in [google/gson#3011](https://redirect.github.com/google/gson/pull/3011)
>
>   The nested classes `ParameterizedTypeImpl`, `GenericArrayTypeImpl`, and `WildcardTypeImpl` in `GsonTypes` are implementations of the corresponding types (without `Impl`) in `java.lang.reflect`. For some reason, they were serializable, even though the `java.lang.reflect` implementations are not. Having unnecessarily serializable classes could *conceivably* have been a security problem if they were part of a larger exploit using serialization. (We do not consider this a likely scenario and do not suggest that you need to update Gson just to get this change.)
> * Add `LegacyProtoTypeAdapterFactory`. by [`@​eamonnmcmanus`](https://github.com/eamonnmcmanus) in [google/gson#3014](https://redirect.github.com/google/gson/pull/3014)
>
>   This is not part of any released artifact, but may be of use when trying to fix code that is currently accessing the internals of protobuf classes via reflection.
> * Make AppendableWriter do flush and close if delegation object supports by [`@​MukjepScarlet`](https://github.com/MukjepScarlet) in [google/gson#2925](https://redirect.github.com/google/gson/pull/2925)
>
> Other less visible changes
> --------------------------
>
> * Add default capacity to EnumTypeAdapter maps by [`@​MukjepScarlet`](https://github.com/MukjepScarlet) in [google/gson#2959](https://redirect.github.com/google/gson/pull/2959)
> * refactor: move derived adapters from Gson to TypeAdapters by [`@​MukjepScarlet`](https://github.com/MukjepScarlet) in [google/gson#2951](https://redirect.github.com/google/gson/pull/2951)
> * Optimize `new Gson()` by [`@​MukjepScarlet`](https://github.com/MukjepScarlet) in [google/gson#2864](https://redirect.github.com/google/gson/pull/2864)
>
> New Contributors
> ----------------
>
> * [`@​ThirdGoddess`](https://github.com/ThirdGoddess) made their first contribution in [google/gson#2944](https://redirect.github.com/google/gson/pull/2944)
> * [`@​lmj798`](https://github.com/lmj798) made their first contribution in [google/gson#2988](https://redirect.github.com/google/gson/pull/2988)
> * [`@​Eng-YasminKotb`](https://github.com/Eng-YasminKotb) made their first contribution in [google/gson#3005](https://redirect.github.com/google/gson/pull/3005)
> * [`@​andrewstellman`](https://github.com/andrewstellman) made their first contribution in [google/gson#3006](https://redirect.github.com/google/gson/pull/3006)
>
> **Full Changelog**: <google/gson@gson-parent-2.13.2...gson-parent-2.14.0>


Commits

* [`3ff35d6`](google/gson@3ff35d6) [maven-release-plugin] prepare release gson-parent-2.14.0
* [`a3024fd`](google/gson@a3024fd) Bump the maven group with 13 updates ([#3002](https://redirect.github.com/google/gson/issues/3002))
* [`5689ffe`](google/gson@5689ffe) Bump the github-actions group across 1 directory with 3 updates ([#3018](https://redirect.github.com/google/gson/issues/3018))
* [`48db33c`](google/gson@48db33c) Add `LegacyProtoTypeAdapterFactory`. ([#3014](https://redirect.github.com/google/gson/issues/3014))
* [`53d703e`](google/gson@53d703e) Update outdated comment regarding serializable types ([#3012](https://redirect.github.com/google/gson/issues/3012))
* [`0189b72`](google/gson@0189b72) Remove `Serializable` from internal `Type` implementation classes. ([#3011](https://redirect.github.com/google/gson/issues/3011))
* [`f4d371d`](google/gson@f4d371d) Fix duplicate key detection when first value is null ([#3006](https://redirect.github.com/google/gson/issues/3006))
* [`27d9ba1`](google/gson@27d9ba1) Fix typo in README (JPMS dependencies section) ([#3005](https://redirect.github.com/google/gson/issues/3005))
* [`1fa9b7a`](google/gson@1fa9b7a) Validate that strings being parsed as integers consist of ASCII characters (#...
* [`b7d5954`](google/gson@b7d5954) Add iterator fail-fast tests for LinkedTreeMap.clear() ([#2992](https://redirect.github.com/google/gson/issues/2992))
* Additional commits viewable in [compare view](google/gson@gson-parent-2.13.2...gson-parent-2.14.0)
  
[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility\_score?dependency-name=com.google.code.gson:gson&package-manager=maven&previous-version=2.13.2&new-version=2.14.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
Dependabot commands and options
  
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot show  ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add Gson.DEFAULT constant

4 participants