9

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.

Tim
  • 2,000
  • 4
  • 27
  • 45
  • 1
    Take a look at this: [http://stackoverflow.com/questions/8982420/time-out-method-in-java][1] [1]: http://stackoverflow.com/questions/8982420/time-out-method-in-java – John Smith Apr 20 '13 at 14:05
  • This helped me achieve my solution, thanks :) – Tim Apr 20 '13 at 17:14

3 Answers3

9

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.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
0

You can use System.nanoTime() inside run method as a condition.

For example,

long cur = System.nanoTime(); //records the time when start executing
...
double elapsedTime(System.nanoTime() - cur) / 1000000.0; // at the end
Eric
  • 2,635
  • 6
  • 26
  • 66
0

Detailed solution with Runnable (see previous thorbjorn's answer):

           ExecutorService executorService = Executors.newSingleThreadExecutor();

           executorService.execute(() ->doFunction()); //here is the Runnable (represented as simple lambda here)

           executorService.shutdown();

           try {
                    if (!executorService.awaitTermination(2000, TimeUnit.MILLISECONDS)) {
                        System.out.println("ERROR: Stopping going to next step");
                     }
            }catch(InterruptedException e){
                   e.printStackTrace();
            }
Myoch
  • 793
  • 1
  • 6
  • 24