更新时间:2022-05-26 08:54:33
绝对不使用计时器
为此!对于一次性运行的桌面应用程序来说很有趣,但是在长期运行的Java EE Web应用程序中使用它时会遇到严重的潜在问题。
Do absolutely not use Timer
for this! It's funny for one-time-run desktop applications, but it has severe potential problems when used in a lifetime long running Java EE web application.
而是使用来自 java.util .concurrent
包。这是一个启动示例:
Rather use the executors from the java.util.concurrent
package. Here's a kickoff example:
ExecutorService executor = Executors.newSingleThreadExecutor(); // An application wide thread pool executor is better.
Callable<InputStream> task = new Callable<InputStream>() {
@Override
public InputStream call() throws Exception {
// Do here your webservice call job.
return new URL("http://***.com").openStream();
}
};
try {
InputStream input = executor.invokeAny(Arrays.asList(task), 60, TimeUnit.SECONDS);
// Successful! Forward to success page here.
} catch (TimeoutException e) {
// Timeout occurred. Forward to timeout page here.
}