Question

how to use a single Java ScriptEngine to perform multiple evaluation synchronously?

for example

method1 includes

sce.eval(code1);

method2 includes

sce.eval(code2);

then the evaluations ran concurrently if both methods synchronized

Was it helpful?

Solution

Synchronized and concurently doesn't fit together as one is the opposite of the other. If the eval method is synchronized you need 2 instances of the scriptengine with the same context, if it is not here comes an explanation on doing parallel/concurrent execufion.

If you want to run both method concurrently, you need more than one thread running as a single thread will sequentially run through it's execution pipeline.

Synchronized means it is thread safe and will queue all the calls made to any synchronized method of a class. For example, if m1 and m2 are synchronized, thread1 calls m1 and thread2 calls m2, the first one that will reach their respctive method will run correctly ehile the second one will wait 'til the other has exit (not totally true) the method to execute the inner code of it's method..

Now, you can take a look at the class Thread, ExecutorService and Executors if you want to run multiple threada at the same time and each will run it's own pipeline/execution atack.

Finally if you want both thread to share the same script engine, you'll have to use the same reference of that object, best way by providing it to the constructor of your object.

But, this is where problems occurs. If the script engine doesn't handle concurrency well, this might lead to some obscur weird behavior so you'll have to read the spec of the scrupt engine and validate if the implementation you are using is thread safe (hence concurrently execution safe).

Simple example :

public void launchAsync(final String code) {
   new Thread() {
       public void run() {
           engine.eval(code);
       }
   }.run();
}

This will execute the code asynchronously than the main thread meaning that calling the method twice will run them in parallel (in a different thread than this one).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top