AKI*_*WEB 15 java multithreading callable resttemplate
我在我的代码中使用Java Callable 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("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
Run Code Online (Sandbox Code Playgroud)
下面是我的Task类,它实现了Callable接口,我需要根据我们拥有的主机名生成URL,然后使用调用SERVERS RestTemplate.如果第一个主机名中有任何异常,那么我将为另一个主机名生成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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题应该声明RestTemplate为静态全局变量?或者在这种情况下它不应该是静态的?
Sot*_*lis 18
无论是哪种方式,都是无关紧要的static.
RestTemplate用于发出HTTP请求的方法是线程安全的,因此无论您是RestTemplate每个Task实例还是所有Task实例的共享实例都是无关紧要的(垃圾收集除外).
就个人而言,我会创建类RestTemplate外部Task并将其作为参数传递给Task构造函数.(尽可能使用控制反转.)
| 归档时间: |
|
| 查看次数: |
14303 次 |
| 最近记录: |