Java ScriptEngine with multiple Threads and Lock

866 views Asked by At

I'm using a JSR223 ScriptEngine (JAV8) which is not thread-safe by itself. Since I need multiple threads to be able to access the ScriptEngine, each ScriptEngine belongs to an EngineContext Object. These EngineContexts again have one ReentrantLock that the individual threads acquire before accessing the ScriptEngine.

The problem I have is that the locks are successfully acquired by the Threads but I still sometimes get JVM crashes (the famous SIGSEGV (0xb)) when two Threads call it.

As an overview, here is some pseudo-code of the locking process

Thread needs the ScriptEngine
Thread waits and acquires lock
Thread uses the ScriptEngine (Methods: eval, put)
Thread releases the lock
Thread does something else

I am really not sure, what the problem here is.

2

There are 2 answers

0
Pepijn Schmitz On

ReentrantLock is supposed to work the same as using synchronized, including the memory effects, but perhaps in this case it does not (perhaps having to do with the native code) and the state of the ScriptEngine is not fully synchronised between the threads. Have you tried using synchronized instead of the ReentrantLock?

If that doesn't help, have you tried having a separate ScriptEngine per thread, for instance using a ThreadLocal? Depending on what kinds of threads these are the overhead that introduces might not be too bad.

0
rxg On

SIGSEGV are always caused by a bug in native code. Assuming that you haven't written any native code yourself, you are either misusing the library, triggering a bug in the library or triggering a bug in the JVM (in decreasing order of likelihood ...).

Without more details from you (code fragment, crash log) it is very hard to tell what your specific problem is.