Results 1 to 3 of 3
Thread: Timeout for a method execution
- 12-22-2008, 03:54 PM #1
Member
- Join Date
- Nov 2008
- Posts
- 17
- Rep Power
- 0
Timeout for a method execution
Hello
I would like to have some help about an issue:
I have a method "doSomething" which can take a while to be fully executed.
I would like to be able to stop the method execution after 10 seconds and continue the normal execution of my class. This means:...
boolean bResult = false;
bResult = doSomething();
System.out.println("Result:" + bResult);
...
- If doSomething() is executed in 3 seconds for example, the System.out.println() statement shows the result of the method
- If doSomething() is executed in more than 10 seconds, after 10 seconds the method is stopped and the System.out.println() will always have false as result.
Anyone can help me about this?
Thanks
regards
- 12-22-2008, 05:53 PM #2
Clarify
What does the doSomething method do?
- Is it calling another method?
- Is it calling/waitng on a process?
- Something else?
Depending on the answer the solution could be different.
CJSLChris S.
Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.
- 12-22-2008, 06:51 PM #3
Stopping a long running method
I can suggest two options.
1. Within the method, assuming it is looping and not waiting for an external event, add a local field and test the time each time around the loop.
2. Run the method in a thread, and have the caller count to 10 seconds.Java Code:void method() { long endTimeMillis = System.currentTimeMillis() + 10000; while (true) { // method logic if (System.currentTimeMillis() > endTimeMillis) { // do some clean-up return; } } }
The drawback to this approach is that method() cannot return a value directly, it must update an instance field to return its value.Java Code:Thread thread = new Thread(new Runnable() { @Override public void run() { method(); } }); thread.start(); long endTimeMillis = System.currentTimeMillis() + 10000; while (thread.isAlive()) { if (System.currentTimeMillis() > endTimeMillis) { // set an error flag break; } try { Thread.sleep(500); } catch (InterruptedException t) {} }
-Steve
Similar Threads
-
Implement a timeout
By pjmorce in forum Advanced JavaReplies: 5Last Post: 04-27-2010, 02:36 AM -
session timeout
By nmbalaji in forum JavaServer Pages (JSP) and JSTLReplies: 4Last Post: 12-12-2008, 04:04 PM -
RAD - Error getting connection: Timeout.
By ShoeNinja in forum Other IDEsReplies: 0Last Post: 09-09-2008, 05:25 PM -
Method execution time
By javaplus in forum Advanced JavaReplies: 3Last Post: 11-26-2007, 09:51 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks