Java: execute a method for a maximum period of time

I use JavaMail API, and there is a method in the Folder class called "search", which sometimes takes too long to complete. I want this method to run for a maximum period of time (for example, a maximum of 15 seconds), so I'm sure this method will not work for more than 15 seconds.

Pseudo code

messages = maximumMethod(Folder.search(),15);

Is it necessary to create a thread only to execute this method, and the wait method in the main thread?

+5
source share
3 answers

- executor, . - Future<?>, . , , . :

    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
    }
+5

  • ,
  • ( ) , , 1 15 . , , .

, , , , , javamail.

,  Stéphane

+1

This SO question shows how to send a timeout exception to client code: How do I call some blocking method with a timeout in Java?

You may be able to interrupt the actual search using Thread.interrupt(), but it depends on the implementation of the method. You can complete the action only to discard the results.

0
source

All Articles