I'm building an javascript api that will call som开发者_开发问答e java objects using mozilla rhino.
Everything is good and nice, however I want to avoid unlimited looping that could slow my java application.
for example (in javascript):
while(true) doSomething(); // doSomthing will call a method in java
In modern browsers after a certain time an error appears telling the script is making the application to run slow, and if I want to continue and stop script.
I want to implement this on my java application if it's possible, but I don't know how. The only solution I can think about is to count the number of methods are being called per second , and if it's a huge number to stop the script. DO you have any other ideas?
Counting the method calls won't work for code that doesn't call any methods, like:
while (true) {
i++;
}
I think what you want is observeInstructionCount(). Also see the discussion here - some of the stuff that they're discussing looks a little iffy, but it might help you.
If you can make the application multithreaded you could spawn a new thread handling each call from javascript. at the start of the thread you record the start time, and create some timeout logic to go with that.
public void doJavaScript() {
final long start = System.currentTimeMillis();
final long timeout = 1000;
new Thread(){
@Override
public void run() {
while ((start + timeout) < System.currentTimeMillis()) {
... do work ...
}
}
}.start();
}
精彩评论