Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip function if it takes too long

In Java I have a function that processes a text file in a certain way. However, if it takes too much time the process will most likely be useless (whatever the reason is) for that text file and I would like to skip it. Furthermore, if the process takes too long, it also uses too much memory. I've tried to solve it this way, but it doesn't work:

for (int i = 0; i<docs.size(); i++){
    try{
        docs.get(i).getAnaphora();
        }
    catch (Exception e){
        System.err.println(e);
    }
 }

where docs is just a List of files in a directory. Usually I have to manually stop the code because it is 'stuck' at a particular file (depending on the contents of that file).

Is there a way of measuring time for that function call and tell Java to skip the file the function takes more than, let's say, 10 seconds?

EDIT
After scraping a few different answers together I came up with this solution which works fine. Perhaps someone else can use the idea as well.

First create a class that implements Runable (this way you can pass in arguments to the Thread if needed):

public class CustomRunnable implements Runnable {

    Object argument;

    public CustomRunnable (Object argument){
        this.argument = argument;
}

    @Override
    public void run() {
        argument.doFunction();
    }
}

Then use this code in the main class to monitor the time of a function (argument.doFunction()) and exit if it takes to long:

Thread thread;
for (int i = 0; i<someObjectList.size(); i++){          
    thread = new Thread(new CustomRunnable(someObjectList.get(i)));
    thread.start();
    long endTimeMillis = System.currentTimeMillis() + 20000;
    while (thread.isAlive()) {
        if (System.currentTimeMillis() > endTimeMillis) {
        thread.stop();
        break;
    }
    try {
        System.out.println("\ttimer:"+(int)(endTimeMillis - System.currentTimeMillis())/1000+"s");
        thread.sleep(2000);
        }
    catch (InterruptedException t) {}
    }
}

I realise stop() is depcecated, but I haven't found any other way to stop and exit the thread when I want it to stop.

like image 693
Tim Avatar asked Apr 20 '13 14:04

Tim


1 Answers

Wrap your code in a Runnable or Callable and submit it to a suitable Executor to execute it. One of the submit method takes a timeout period after which has passed the code is interrupted.

like image 90
Thorbjørn Ravn Andersen Avatar answered Oct 17 '22 11:10

Thorbjørn Ravn Andersen