1 package jep.test;
2 
3 import jep.Interpreter;
4 import jep.SharedInterpreter;
5 
6 /**
7  * Tests that jep works without using sub-interpreters and verified that all
8  * modules are shared between interpreters on different threads.
9  *
10  * Created: Jan 2018
11  *
12  * @author Ben Steffensmeier
13  */
14 public class TestSharedInterpreter extends Thread {
15 
main(String[] args)16     public static void main(String[] args) throws Throwable {
17         TestSharedInterpreter[] t = new TestSharedInterpreter[4];
18         try (Interpreter interp = new SharedInterpreter()) {
19             interp.eval("import sys");
20             interp.set("n", t.length);
21             interp.eval("sys.sharedTestThing = [None] * n");
22         }
23 
24         for (int i = 0; i < t.length; i += 1) {
25             t[i] = new TestSharedInterpreter(i);
26             t[i].start();
27         }
28         for (int i = 0; i < t.length; i += 1) {
29             t[i].join();
30             if (t[i].e != null) {
31                 throw t[i].e;
32             }
33         }
34         try (Interpreter interp = new SharedInterpreter()) {
35             for (int i = 0; i < t.length; i += 1) {
36                 interp.eval("import sys");
37                 interp.set("i", i);
38                 Boolean b = (Boolean) interp.getValue("sys.sharedTestThing[i]");
39                 if (b.booleanValue() == false) {
40                     throw new IllegalStateException(i + " failed");
41                 }
42             }
43         }
44     }
45 
46     public Exception e = null;
47 
48     public final int index;
49 
TestSharedInterpreter(int index)50     public TestSharedInterpreter(int index) {
51         this.index = index;
52     }
53 
54     @Override
run()55     public void run() {
56         try (Interpreter interp = new SharedInterpreter()) {
57             interp.eval("import sys");
58             interp.set("index", index);
59             interp.eval("sys.sharedTestThing[index] = True");
60         } catch (Exception e) {
61             this.e = e;
62         }
63     }
64 
65 }
66