简体   繁体   中英

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. 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.

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 ?

The best way to do this is create a single threaded executor which you can submit callables with. The return value is a Future<?> which you can get the results from. 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

  1. mark current time
  2. launch a thread that will search in the folder
  3. while you get the result (still in thread) don't do anything if current time exceeds time obtained in 1 plus 15 seconds. You won't be able to stop the connection if it is pending but you could just disgard a late result.

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.

Regards, 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?

You might be able to interrupt the actual search using Thread.interrupt() , but that depends on the method's implementation. You may end up completing the action only to discard the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM