Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 692
tt0686 Avatar asked Aug 24 '11 14:08

tt0686


People also ask

How do you create a time limit in Java?

To set the time limit of a search, pass the number of milliseconds to SearchControls. setTimeLimit(). The following example sets the time limit to 1 second. // Set the search controls to limit the time to 1 second (1000 ms) SearchControls ctls = new SearchControls(); ctls.

How to stop a thread after some time in Java?

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.

How to halt execution in Java?

In Java exit() method is in java. exit() method terminates the current JVM running on the system which results in termination of code being executed currently.


1 Answers

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
    }
like image 132
Amir Raminfar Avatar answered Oct 19 '22 00:10

Amir Raminfar