Skip function if it takes too long

↘锁芯ラ 提交于 2019-12-12 08:02:10

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/16121176/skip-function-if-it-takes-too-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!