gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:38:35 24 4
gpt4 key购买 nike

我在代码中使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com