Search code examples
javamultithreadinggsonpool

Does Gson performance benefit from a resource pool in highly multi-threaded applications?


I'm working on a highly multi-threaded Java application in which a single global Gson instance is shared between a large number of threads. At the moment I haven't noticed any performance deterioration however the volume of Json being processed has been relatively low up until now.

I was wondering if it would make sense to create a resource pool of Gson instances which every thread acquires and releases Gson instances from/to? To be specific, would it avoid scenarios where a thread is blocked waiting for access to the global Gson instance?

the Gson documentation mentions: "Gson instances are Thread-safe so you can reuse them freely across multiple threads.". However I'm having trouble figuring out whether this means it simply locks until it is done or if it uses some internal resource pool.


Solution

  • I was wondering if it would make sense to create a resource pool of Gson instances which every thread acquires and releases Gson instances from/to?

    No, it wouldn't. Gson thread-safety is accomplished by its immutability and creator/factory-like design. You cannot change a Gson instance once its created, and the Gson class does not provide any way of doing so:

    • It's immutable and its state cannot be changed from outside (it does not provide methods that can change its state + its fields are declared final to express this intent).
    • It also does not allow to change its state transitively (say, it does not let you get a private field via a "get" method and change the object from outside).

    Since there is nothing to modify in a Gson instance, it does not need synchronization mechanisms for read-only semantics:

    • You don't need to pay for what you won't typically use (synchronized has its cost).
    • It keeps its design and implementation simple.

    Therefore invoking any Gson method is thread-safe, but the objects returned from these methods may lack thread-safety (for example, JsonReader/JsonWriter are not thread-safe; JsonElement and its subclasses may be thread-unsafe; etc). Having this in mind you must be sure that your type adapters (Gson serializers/deserializers) are thread-safe by their design and do not change their internal state -- Gson relies on this heavily (as far as I know, all Gson built-in type adapters are immutable). Obviously, if a particular type adapter uses synchronization mechanisms (and it's clearly a bottleneck), Gson from and to methods may await if they use such a type adapter, but you'd still be able to use Gson instance from other threads (however I would never design, implement and use type adapters that use synchronization under the hood).

    So,

    a single global Gson instance is shared between a large number of threads

    is totally fine.