Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should GSON be declared as static final?

I am using Java Callable Future in my code. Below is my main code which uses the future and callables -

Below is my main code which uses the future and callables -

public class TimeoutThread {

    public static void main(String[] args) throws Exception {

        ExecutorService executor = Executors.newFixedThreadPool(5);
        Future<TestResponse> future = executor.submit(new Task());

        try {
            System.out.println(future.get(3, TimeUnit.SECONDS));
        } catch (TimeoutException e) {

        }

        executor.shutdownNow();
    }
}

Below is my Task class which implements the Callable interface in which I am making a REST URL call to my SERVERS using RestTemplate. And then I am passing response variable to checkString method in which I am deserializing the JSON string and then I am checking whether the key has error or warning in it and then basis on that make a TestResponse.

class Task implements Callable<TestResponse> {
    private static RestTemplate restTemplate = new RestTemplate();

    @Override
    public TestResponse call() throws Exception {

    String url = "some_url";            
    String response = restTemplate.getForObject(url, String.class);

    TestResponse response = checkString(response);
    }
}

private TestResponse checkString(final String response) throws Exception {

    Gson gson = new Gson(); // is this an expensive call here, making objects for each and every call?
    TestResponse testResponse = null;
    JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse, need to check whether it is an expensive call or not.
    if (jsonObject.has("error") || jsonObject.has("warning")) {

        final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
            .get("warning").getAsString();

        testResponse = new TestResponse(response, "NONE", "SUCCESS");
    } else {
        testResponse = new TestResponse(response, "NONE", "SUCCESS");
    }

    return testResponse;
}

So my question is how should I declare GSON here? Should it be declared as static final global variable in my Task class? Bcoz currently I am parsing JSON using gson and for every call I am making new Gson() which would be expensive or not?

like image 939
AKIWEB Avatar asked Feb 11 '14 17:02

AKIWEB


People also ask

Can GSON be static?

By default, Gson excludes transient or static fields from consideration for serialization and deserialization. You can change this behavior through GsonBuilder.

Does GSON serialize static fields?

Nested Classes (including Inner Classes)Gson can serialize static nested classes quite easily.

Is GSON instance 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.

How does GSON from JSON work?

Gson can work with arbitrary Java objects including objects for which you do not have the source. For this purpose, Gson provides several built in serializers and deserializers. A serializer allows to convert a Json string to corresponding Java type. A deserializers allows to convert from Java to a JSON representation.


2 Answers

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.

Note that if you want your client code to be able to customize the rendering by using GsonBuilder, you should accept a Gson object as a parameter.

like image 200
chrylis -cautiouslyoptimistic- Avatar answered Oct 08 '22 02:10

chrylis -cautiouslyoptimistic-


The Gson library can be defined at the class level and be used everywhere because it does not maintain state across different invocations. Since it doesn't maintain state, you can declare it once and use it everywhere (one less line of code if you need to reuse it). Multi threading will have no effect on it. On another note though, looking at it's performance metrics in it's official documentation, it doesn't seem to be an expensive call.

like image 28
ucsunil Avatar answered Oct 08 '22 03:10

ucsunil