在执行过程中停止Rhino引擎

时间:2012-04-20 12:13:21

标签: java rhino

Rhino引擎是否有api可以停止执行a 剧本在中间。例如,我有一个脚本文件 有一个infinte循环。如何在中间停止执行?

当然,我可以停止启动Rhino引擎的jvm 除了脚本。但是我不想因为这个原因而杀死整个jvm会话,因为我已经以编程方式启动了脚本,并且Rhino Engine也在与我的应用程序相同的JVM中运行。

4 个答案:

答案 0 :(得分:6)

可以使用以下方式停止执行正在运行的JavaScript。

1)创建一个虚拟调试器并将其附加到最初创建的上下文中。

mContext = Context.enter();
ObservingDebugger observeingDebugger = new ObservingDebugger();
mContext.setDebugger(observingDebugger,new Integer(0));
mContext.setGeneratingDebug(真);
mContext.setOptimizationLevel(-1);

ObservingDebugger代码如下所示。

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.debug.DebugFrame;
import org.mozilla.javascript.debug.DebuggableScript;
import org.mozilla.javascript.debug.Debugger;

public class ObservingDebugger implements Debugger 
{
boolean isDisconnected = false;

private DebugFrame debugFrame = null;

public boolean isDisconnected() {
    return isDisconnected;
}

public void setDisconnected(boolean isDisconnected) {
    this.isDisconnected = isDisconnected;
    if(debugFrame != null){
       ((ObservingDebugFrame)debugFrame).setDisconnected(isDisconnected);
    }
}

public ObservingDebugger() {

}

public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript)
{
    if(debugFrame == null){
        debugFrame = new ObservingDebugFrame(isDisconnected);
    }
    return debugFrame;      
}

@Override
public void handleCompilationDone(Context arg0, DebuggableScript arg1, String arg2) {   } }
// internal ObservingDebugFrame class
class ObservingDebugFrame implements DebugFrame
   {
boolean isDisconnected = false;

public boolean isDisconnected() {
    return isDisconnected;
}

public void setDisconnected(boolean isDisconnected) {
    this.isDisconnected = isDisconnected;
}

ObservingDebugFrame(boolean isDisconnected)
{
    this.isDisconnected = isDisconnected;
}

public void onEnter(Context cx, Scriptable activation,
        Scriptable thisObj, Object[] args)
{ }

public void onLineChange(Context cx, int lineNumber) 
{
    if(isDisconnected){
        throw new RuntimeException("Script Execution terminaed");
    }
}

public void onExceptionThrown(Context cx, Throwable ex)
{ }

public void onExit(Context cx, boolean byThrow,
        Object resultOrException)
{ }

@Override
public void onDebuggerStatement(Context arg0) { } }

ObservingDebugger类将管理布尔变量“isDisconnected”,当用户单击停止按钮(想要停止执行)时,此变量将设置为true。一旦变量设置为true,如下所示,Rhino Execution将立即终止。

observingDebugger.setDisconnected(true);

答案 1 :(得分:2)

对于其他寻找解决方案的人来说,ContextFactory的javadoc详细说明了如何停止运行超过10秒的脚本:

https://github.com/mozilla/rhino/blob/master/src/org/mozilla/javascript/ContextFactory.java

答案 2 :(得分:0)

我使用ExecutorService和timed-out future.get

在新线程中执行脚本
    ExecutorService executor = Executors.newSingleThreadExecutor();

    Future<?> future = executor.submit(threadEvaluation);

    try {
        System.out.println("Started..");
        future.get(100, TimeUnit.MILLISECONDS);
        System.out.println("Finished!");
    } catch (TimeoutException e) {
        future.cancel(true);
        System.out.println("Terminated!");
    }

请注意,此方法不会停止执行脚本的线程!为了做到这一点,当执行脚本的线程被通知中断时,您可以创建一个定制监视这种情况的自定义ContextFactory:

public class InterruptableContextFactory extends ContextFactory {

    public static boolean initialized = false;

    public static void init() {
        if (!initialized) {
            ContextFactory.initGlobal(new InterruptableContextFactory());
            initialized = true;
        }
    }

    @Override
    protected void observeInstructionCount(Context cx, int instructionCount) {
        System.out.println(instructionCount + " javascript instructions!");
        if (Thread.currentThread().isInterrupted()) {
            throw new Error("script execution aborted");
        }
    }

    @Override
    protected Context makeContext() {
        Context cx = super.makeContext();
        //set a number of instructions here
        cx.setInstructionObserverThreshold(10000);
        return cx;
    }
}

在创建任何Context对象之前,您需要将应用程序配置为使用此ContextFactory作为默认值,只需调用

InterruptableContextFactory.init()

在您的Callable调用方法中,您可以捕获错误:

    try {
        cx.setOptimizationLevel(9);
        cx.setInstructionObserverThreshold(10000);
        ScriptableObject scope = cx.initStandardObjects();

        // your code here

    } catch (Error e) {
        System.out.println("execution was aborted: " + e.getMessage());
    } finally {
        Context.exit();
    }

答案 3 :(得分:-2)

Rhino引擎doesn't appear有任何机制来执行此操作(糟糕的Rhino!)并且很难判断它是否在内部创建线程,因此您获得的唯一解决方案是创建{{3}从该组中的线程内部加载并执行Rhino引擎及其脚本,当您想要将其终止时,请使用ThreadGroup。是的,它被弃用了但是由于Rhino库没有合作,所以没有别的方法可以做到。