【发布时间】:2017-04-26 04:56:38
【问题描述】:
我希望能够捕获一个延续并多次恢复它,这样每个这样的调用都将独立于其他调用。
例如,在以下代码中,我希望在 run 方法中对 context.resumeContinuation 的 2 次调用产生输出:1 1,而不是 1 2 的当前输出。
据我了解,产生输出的原因是我始终使用相同的 scope 对象,该对象在传递给第二个延续之前由第一个延续进行修改。因此,我似乎应该使用原始scope 的副本 来恢复每个延续,但类型Scriptable 没有clone 方法(或任何等效方法),并使用序列化/反序列化复制它也无济于事。
P.S.我使用的是 Rhino 1.7R5 版本。
Example.java:
import org.mozilla.javascript.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Example {
public void run() throws IOException {
Context context = Context.enter();
context.setOptimizationLevel(-2); // Use interpreter mode.
Scriptable scope = context.initStandardObjects();
scope.put("javaProxy", scope, Context.javaToJS(this, scope));
Object capturedContinuation = null;
try {
String scriptSource =
new String(Files.readAllBytes(Paths.get("example.js")));
String scriptName = "example";
int startLine = 1;
Object securityDomain = null;
Script script =
context.compileString(scriptSource, scriptName, startLine, securityDomain);
context.executeScriptWithContinuations(script, scope);
} catch (ContinuationPending continuationPending) {
capturedContinuation = continuationPending.getContinuation();
}
Object result = "";
context.resumeContinuation(capturedContinuation, scope, result);
context.resumeContinuation(capturedContinuation, scope, result);
Context.exit();
}
public void captureContinuation() {
Context context = Context.enter();
ContinuationPending continuationPending =
context.captureContinuation();
Context.exit();
throw continuationPending;
}
public void print(int i) {
System.out.print(i + " ");
}
public static void main(String[] args) throws IOException {
new Example().run();
}
}
example.js:
var i = 1;
javaProxy.captureContinuation();
javaProxy.print(i);
i = i + 1;
【问题讨论】:
标签: java rhino continuations