Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to use Gson instance as a static field in a model bean (reuse)?

People also ask

Can Gson be reused?

Gson instances are Thread-safe so you can reuse them freely across multiple threads. You can create a Gson instance by invoking new Gson() if the default configuration is all you need.

Should Gson objects be static?

The Gson object is explicitly safe to use from multiple threads, as it doesn't keep any internal state, so yes, declare a private static final Gson GSON = new Gson(); , or even make it public .

Is Gson toJson Thread-safe?

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.

Does Gson ignore transient fields?

Gson serializer will ignore every field declared as transient: String jsonString = new Gson().


It seems just fine to me. There is nothing in the GSON instance that makes it related to a specific instance of LoginSession, so it should be static.

GSON instances should be thread-safe, and there was a bug regarding that which was fixed.


The core Gson class is thread-safe. I just encountered a thread-safety issue that was supposedly with GSON. The issue happened when using a custom JsonDeserializer and JsonSerializer for Date parsing and formatting. As it turned out, the thread-safety issue was with my method's use of a static SimpleDateFormat instance which is not thread-safe. Once I wrapped the static SimpleDateFormat in a ThreadLocal instance, everything worked out fine.


According to the comments the existing unit test does not really test much, be careful with anything related to thread safety...

There is a unit test checking for thread safety:

/**
 * Tests for ensuring Gson thread-safety.
 *
 * @author Inderjeet Singh
 * @author Joel Leitch
 */
public class ConcurrencyTest extends TestCase {
  private Gson gson;
  ...

You may wonder if this unit test is sufficient to find every possible problem on every possible machine configuration ? Any comments on this ?

There is also this sentence in the docs:

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.


We had issues with thread safety a while back and we solved it by using the FastDateFormat in apache commons.

Just created a gist Link for Gist around this to help the people wondering if Gson instances can be reused. They do not have setters and all vars are private.

So other than the SimpleDateFormat issue I don't see them maintaining state anywhere else.

Do check it out. This is my first time replying to one of these . Happy to give back for once . :)