【发布时间】:2014-02-04 09:39:14
【问题描述】:
我在我的代码中使用 Java Callable Future。下面是我使用未来和可调用对象的主要代码 -
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("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
下面是我的Task 类,它实现了Callable 接口,我需要根据我们拥有的主机名生成URL,然后使用RestTemplate 调用SERVERS。如果第一个主机名有任何异常,那么我将为另一个主机名生成 URL,然后我会尝试拨打电话。
class Task implements Callable<String> {
private static RestTemplate restTemplate = new RestTemplate();
@Override
public String call() throws Exception {
//.. some code
for(String hostname : hostnames) {
if(hostname == null) {
continue;
}
try {
String url = generateURL(hostname);
response = restTemplate.getForObject(url, String.class);
// make a response and then break
break;
} catch (Exception ex) {
ex.printStackTrace(); // use logger
}
}
}
}
所以我的问题是我应该将RestTemplate 声明为静态全局变量吗?或者在这种情况下它不应该是静态的?
【问题讨论】:
标签: java multithreading resttemplate callable