java - GSON 是否应该被声明为 static final?

标签 java multithreading thread-safety gson

我在代码中使用 Java Callable Future。下面是我的主要代码,它使用了 future 和 callables -

下面是我的主要代码,它使用了 future 和 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();
    }
}

下面是我的 Task 类,它实现了 Callable 接口(interface),在该接口(interface)中我使用 RestTemplate 对我的服务器进行 REST URL 调用。然后我将 response 变量传递给 checkString 方法,在该方法中我反序列化 JSON 字符串,然后检查 key 是否有 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;
}

所以我的问题是我应该如何在这里声明GSON?是否应该在我的 Task 类中将其声明为静态最终全局变量? Bcoz 目前我正在使用 gson 解析 JSON,并且每次调用 new Gson() 都会很昂贵吗?

最佳答案

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

请注意,如果您希望您的客户端代码能够使用 GsonBuilder 自定义呈现,您应该接受一个 Gson 对象作为参数。

关于java - GSON 是否应该被声明为 static final?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21709219/

相关文章:

java - 在 GAE 客户端上使用 OAuth 2.0(身份验证) token

java - 在简单计算器中验证数学运算符

multithreading - “current vertex declaration does not include all the elements required”

ruby - 无法使套接字接受非阻塞 ruby​​ 2.2

java - ThreadLocal 和列表不起作用

java - 无法应用插件 'com.google.protobuf'

java - Android-通过ArrayList时应用崩溃

java - RequestContextHolder.getRequestAttributes() 在 @Async 之后获取 null

Java JProgressBar 不通过 setVisible(true) 显示

Ruby ||= 运算符线程安全