hi i want a block of code(certain lines of a function) that will run for a stipulated amount of time (say x milliseconds).Is is possible to do this in java?
- 2What's going to happen after agreed amount of time passed? Timing out?Boris Pavlović– Boris Pavlović2011-01-10 17:01:53 +00:00Commented Jan 10, 2011 at 17:01
- See also Java: set timeout on a certain block of codeVadzim– Vadzim2018-11-27 21:36:16 +00:00Commented Nov 27, 2018 at 21:36
5 Answers
either use an exit condition based on current timestamp, or create a separate thread and kill it after a specified timeout.
2 Comments
Run your method in a separate thread, but passing it to an Executor. You can then use the Future to wait a certain period of time for the the thread to complete. If it doesn't complete, you will get a TimeoutException and you can then cancel the thread. Cancelling the thread causes the thread to be interrupted. So your code will have to periodically check the thread's interrupted status and exit if necessary.
For example:
ExecutorService exec = Executors.newSingleThreadExecutor(); Future<Integer> future = exec.submit(new Callable<Integer>(){ @Override public Integer call() throws Exception { //do some stuff //periodically check if this thread has been interrupted if (Thread.currentThread().isInterrupted()) { return -1; } //do some more stuff //check if interrupted if (Thread.currentThread().isInterrupted()) { return -1; } //... and so on return 0; } }); exec.shutdown(); try { //wait 5 seconds for the task to complete. future.get(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { //the task did not complete in 5 seconds e.printStackTrace(); System.out.println("CANCELLING"); //cancel it future.cancel(true); //sends interrupt } Comments
Check the time using System.currentTimeMillis() and exit your loop after the time has passed.
long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS; while (System.currentTimeMillis() < endTime) { // do your stuff } If you need to sleep inside the thread for some reason, adjust your sleep time to end at the end time.
long timeLeft = endTime - System.currentTimeMillis(); if (sleepAmount > timeLeft) sleepAmount = timeLeft; Thread.sleep(sleepAmount);
If you're going to use the wait() and notify() method, then use the calculated timeLeft as the argument to wait() to ensure the maximum wait time. Once that wait time hits, the method will return and the loop will break.
long timeLeft = endTime - System.currentTimeMillis(); if (timeLeft > 0) this.wait(timeLeft);
If you're running multiple steps inside the loop which can take a long time, you should add additional checks between steps, if you want the process to break between steps, to exit the loop if the designated time has passed. This is a design decision. When the timer expires, do you want the task to finish up the step it's working on and then exit? It's up to you how to code it based on the desired result.
long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS; while (System.currentTimeMillis() < endTime) { this.doFirstLongThing(); if (System.currentTimeMillis() >= endTime) break; this.doSecondLongThing(); if (System.currentTimeMillis() >= endTime) break; this.doThirdLongThing(); }