0

Say I have a method called doSomething, and I call the method like this:

int result = doSomething();

And suppose doSomething() takes 500ms to execute by default. However, I want to halt the execution of doSomething() if it goes over the limit of 300ms. Would it be possible to do that in Java?

I tried the following which didn't work:

    int res;
    long timestart = System.currentTimeMillis();
    long timeend = timestart + 30;
    while(System.currentTimeMillis() < timeend) {
        res = doSomething();
    }
swing1234
  • 233
  • 1
  • 3
  • 13
  • 1
    https://stackoverflow.com/questions/1164301/how-do-i-call-some-blocking-method-with-a-timeout-in-java – JonR85 Oct 15 '21 at 17:53
  • 1
    This isn't really practical to do unless `doSomething` checks the time limit itself, or responds to interrupts, or in some way cooperates with cancellation. – Louis Wasserman Oct 15 '21 at 18:06

0 Answers0