1

I have a question regarding Singleton class behavior.

Scenario
We have webservices that is used by partners with request coming as frequently as 2-3 times in 1 second. So, they are heavily used services. We would like to store the request and response in JSON format.

As of now, in each webservice interface class, we have initiated Gson object and doing the serialization of java object to json.

Question
I was just thinking if I initiate Gson object once in Singleton class as static object and then refer it for all the request / response serialization of java object to Json, can it cause any issue/problem?

I mean, as there are multiple webservices and couple of them are heavily used by partners, so will single instance of GSON accessed in all the webservice can cause any delay or any other problem? If yes, apart than memory, what are the other benefits and issues with it?

vnkotak
  • 129
  • 4
  • 14
  • Possible duplicate of [Is it OK to use Gson instance as a static field in a model bean (reuse)?](http://stackoverflow.com/questions/10380835/is-it-ok-to-use-gson-instance-as-a-static-field-in-a-model-bean-reuse) – Lyubomyr Shaydariv Mar 31 '17 at 09:09

2 Answers2

2

From javadoc of Gson:

This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

So it's ok to have only one Gson instance in your service and reuse it for each request/response. As an example you can consider to create a util class, something like the following class:

public abstract class GsonUtils {
    private static Gson gson = new Gson();

    static {
        // your extra init logic goes here
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        return gson.fromJson(json, classOfT);
    }


    public static String toJson(Object object) {
        if (object == null) {
            return "";
        }
        return gson.toJson(object);
    }
}

Or you can do it in your way :-)

shizhz
  • 11,715
  • 3
  • 39
  • 49
0

Recently I was dealing with same idea. There is older thread related to this Is it OK to use Gson instance as a static field in a model bean (reuse)?. Simply summarised the GSON instance should be thread safe.

Community
  • 1
  • 1
RadekSohlich
  • 182
  • 1
  • 3
  • 11