GSON应该被宣布为静态决赛吗?

AKI*_*WEB 8 java multithreading thread-safety gson

我在我的代码中使用Java Callable Future.下面是我使用未来和callables的主要代码 -

下面是我使用未来和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();
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的Task类,它实现了Callable接口,我在其中使用REST来调用我的SERVERS RestTemplate.然后我传递response变量checkString的方法,其中,我反序列化JSON字符串,然后我检查开关是否有errorwarning在它,然后在此基础上做出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;
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是我该如何申报GSON?它应该在我的Task类中声明为静态最终全局变量吗?Bcoz目前我正在使用gson解析JSON,并且对于我正在制作的每个电话,new Gson()这些电话会不会很昂贵?

chr*_*ke- 13

Gson对象在多个线程中使用是明确安全的,因为它不保留任何内部状态,所以是的,声明一个private static final Gson GSON = new Gson();,甚至是它public.

请注意,如果您希望客户端代码能够使用自定义渲染GsonBuilder,则应接受Gson对象作为参数.

  • +1:这是关于在json运营期间不维护任何状态的官方说法https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson (2认同)