我在代码中使用 Java Callable Future。下面是我的主要代码,它使用了 future 和 callables -
下面是我的主要代码,它使用了 future 和 callables -
public class TimeoutThread {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<String> 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 调用。然后使用 GSON
反序列化 JSON 字符串。
class Task implements Callable<String> {
private static RestTemplate restTemplate = new RestTemplate();
@Override
public String call() throws Exception {
String url = "some_url";
String response = restTemplate.getForObject(url, String.class);
TestResponse jsonResponse = new Gson().fromJson(response, TestResponse.class);
}
}
所以我的问题是我应该如何在这里声明GSON
?是否应该在 Task 类中将其声明为静态全局变量? Bcoz 目前我正在使用 gson 解析 JSON,并且每次调用 new Gson()
这会很昂贵吗?
最佳答案
Gson
类的源代码在这里:https://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/Gson.java
它只有 final
字段,因此它的内部状态是不可变的。所有引用的集合都包装为 synchronizedMap
或 unmodifiableList
。 toJson
和 fromJson
方法主要依赖于局部变量。因此共享同一个实例是安全的。
关于java - 我应该如何声明 GSON 来反序列化 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324764/