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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With