4

Currently, I have a lot of occurences in my code that read as follows: result = new Gson().fromJson(someString, ResultContainer.class); Should I share the GSON object over all those places? If so, per object or static per class (potentially even superclass?)

I am asking mainly because if sharing the reference statically is fine, then why isn't the Gson object static in the first place? Unless one uses fancy custom serialization rules, the method above pretty much covers what one would want Gson to do.

Janis F
  • 2,637
  • 1
  • 25
  • 36
  • It's not singleton because you can configure it differently via `GsonBuilder`. See [javadoc](https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html#Gson()). – Andy Turner Oct 06 '15 at 11:17

2 Answers2

4

According to the GSON user guide:

The Gson instance does not maintain any state while invoking Json operations. So, you are free to reuse the same object for multiple Json serialization and deserialization operations.

It's not singleton because you can configure it differently via GsonBuilder.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

Sharing the Gson is fine.

You can configure a Gson using GsonBuilder therefore Gsonis not a singleton.

wero
  • 32,544
  • 3
  • 59
  • 84
  • it is my experience that it is fine to share, but I can't see anywhere in the doc which says it is so. Can you add a link maybe? – Andy Turner Oct 06 '15 at 11:19
  • Ah, found it myself; added my own answer. – Andy Turner Oct 06 '15 at 11:21
  • @AndyTurner the Gson team should have definitely put the user guide statement into the Javadoc... – wero Oct 06 '15 at 11:24
  • I must have found an old version of the source, since it does mention thread safety at head: https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/Gson.java – Andy Turner Oct 06 '15 at 11:30
  • @AndyTurner excellent, they corrected this themselves https://github.com/google/gson/commit/0c4ae018361d4756123c82c2f67ad04385caec5b – wero Oct 06 '15 at 11:33