This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Java in General and the fly likes running of code within a specified time limit Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "running of code within a specified time limit" Watch "running of code within a specified time limit" New topic
Author

running of code within a specified time limit

Ind Sans
Greenhorn

Joined: Jan 07, 2010
Posts: 11
Hi,
Is there any API or options wherein lines of codes are executed within a specified time.

For example:

StartTimer<current time>
code line 1
code line 2
code line 3
code line 4 ---- The code execution stops here itself without proceeding since the given time limit has ended.
code line 5
EndTimer<Current time+10 seconds>


thanks in advance

bharat
Nicola Garofalo
Ranch Hand

Joined: Apr 10, 2010
Posts: 308
You could use Thread.sleep(ms) method. Here's a code snippet



but..perhaps i got it wrong..you want all the 5 lines to be executed within a time limit...


Bye,
Nicola
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19684
    
  20

Run the code in a different thread, then use join:
There is no real way of actually terminating the thread though, so the code will continue in the background. Maybe interrupting the thread can help but I'm not sure.

Alternatively, check out java.util.concurrent.Future. That's a class with a timed get() method that can be canceled.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Michael Angstadt
Ranch Hand

Joined: Jun 17, 2009
Posts: 273

You could just check the time manually, though this is very tedious:



Or you could use an interface with a List of anonymous classes so you can loop over all the lines:



SCJP 6 || SCWCD 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: running of code within a specified time limit