public
Created

Nashorn Threading Problem

  • Download Gist
SSCCE.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
import javax.script.CompiledScript;
import javax.script.Compilable;
import javax.script.ScriptException;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import java.util.concurrent.Future;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Callable;
import java.util.ArrayList;
public class SSCCE {
private static final NashornScriptEngineFactory engineFactory = new NashornScriptEngineFactory();
public static void main(String[] args) throws ScriptException, InterruptedException, ExecutionException {
Compilable engine = (Compilable) engineFactory.getScriptEngine();
String script = new StringBuilder("i = 0;")
.append("i += 1;")
.append("shortly_later = new Date()/1000 + Math.random;") // 0..1 sec later
.append("while( (new Date()/1000) < shortly_later) { Math.random() };") //prevent optimizations
.append("i += 1;")
.toString();
final CompiledScript onePlusOne = engine.compile(script);
Callable<Double> addition = new Callable<Double>() {
@Override
public Double call() {
try {
return (Double) onePlusOne.eval();
}
catch(ScriptException e) {
throw new RuntimeException(e);
}
}
};
ExecutorService executor = Executors.newCachedThreadPool();
ArrayList<Future<Double>> results = new ArrayList<Future<Double>>();
for(int i = 0; i < 50; i++) {
results.add(executor.submit(addition));
}
int miscalculations = 0;
for(Future<Double> result : results) {
int jsResult = result.get().intValue();
if(jsResult != 2) {
System.out.println("Incorrect result from js, expected 1 + 1 = 2, but got " + jsResult);
miscalculations += 1;
}
}
executor.awaitTermination(1, TimeUnit.SECONDS);
executor.shutdownNow();
System.out.println("Overall: " + miscalculations + " wrong values for 1 + 1.");
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.