[英]java : execute a method over a maximum period of time
I am using the JavaMail API
, and there is a method in the Folder class called "search" that sometimes take too long to execute. 我正在使用
JavaMail API
,在Folder类中有一个名为“search”的方法,有时执行时间太长。 What i want is to execute this method over a maximum period of time( say for example 15 seconds in maximum) , that way i am sure that this method will not run up more than 15 seconds. 我想要的是在最长的时间段内执行此方法(例如最多15秒),这样我确信此方法不会超过15秒。
Pseudo Code 伪代码
messages = maximumMethod(Folder.search(),15);
Do I have to create a thread just to execute this method and in the main thread use the wait method ? 我是否必须创建一个线程来执行此方法,并在主线程中使用wait方法?
The best way to do this is create a single threaded executor which you can submit callables with. 执行此操作的最佳方法是创建一个单线程执行程序 ,您可以使用它来提交callables。 The return value is a
Future<?>
which you can get the results from. 返回值是
Future<?>
,您可以从中获取结果。 You can also say wait this long to get the results. 你也可以说等这么久才能得到结果。 Here is sample code:
这是示例代码:
ExecutorService service = Executors.newSingleThreadExecutor();
Future<Message[]> future = service.submit(new Callable<Message[]>() {
@Override
public Message[] call() throws Exception {
return Folder.search(/*...*/);
}
});
try {
Message[] messages = future.get(15, TimeUnit.SECONDS);
}
catch(TimeoutException e) {
// timeout
}
You could 你可以
Also, if you have access to the socket used to search the folder, you could set its timeout but I fear it's gonna be fully encapsulated by javamail. 此外,如果您有权访问用于搜索文件夹的套接字,您可以设置其超时但我担心它将被javamail完全封装。
Regards, Stéphane 此致,Stéphane
This SO question shows how to send a timeout exception to the client code: How do I call some blocking method with a timeout in Java? 这个SO问题显示了如何向客户端代码发送超时异常: 如何在Java中使用超时调用某些阻塞方法?
You might be able to interrupt the actual search using Thread.interrupt()
, but that depends on the method's implementation. 您可以使用
Thread.interrupt()
中断实际搜索,但这取决于方法的实现。 You may end up completing the action only to discard the results. 您可能最终只完成操作以丢弃结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.