1

Currently I am using the Google's Gson class to parse incoming Ajax JSON strings into Java pojos, as part of the doGet/doPost tasks. I instantiate a new Gson object the usual out from the JSON string the usual way:

JsonObj jsonObj = new Gson().fromJson(jsonStr, jsonObj.class);

The doubt is if I should instantiate a shared gson object in the servlet initialization to avoid doing new Gson() in every servlet doGet/doPost call.

Here Instantiate a new instance of GSON for every serialization? I've learnt that Gson is not a singleton and that some customization is possible with GsonBuilder, but this is not my case. I am worried about the multithreading behavior of the shared Gson object.

coterobarros
  • 941
  • 1
  • 16
  • 25

1 Answers1

1

Simple answer: Gson is thread safe and you can share it between servlets. See: Is it OK to use Gson instance as a static field in a model bean (reuse)?

But you should decouple JSON serialization/deserialization logic from your business logic. For example, in Spring is done by *HttpMessageConverter layer. So, first step would be to create shared bean of Gson object and second would be creating abstract layer which allow to exchange implementation if it is needed. If you are writing web-app anyway, Spring is a good choice.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146