Scala Script Engine creating another instance of a singleton

So, I'm creating a scripting system using JSR 223 for Scala, but I came across this problem I can't find any cause for.

There is a singleton-like class, which has methods to add event listeners (from the scripts) and dispatch events (from the core). Everything worked fine, but for some reason the added listeners had disappeared when I got to dispatch an event.

After reproducing the problem, I found out that the script engine creates another instance of the singleton:

Here is my Singleton class:

package test;

import java.util.Arrays;

public final class Singleton {

    private static final Singleton instance = new Singleton();

    private Singleton() {;

    public static Singleton instance() {
        return instance;

And here is my Main class:

package test;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public final class Main {

    public static void main(String[] args) throws ScriptException {

        ScriptEngine engine = new ScriptEngineManager().getEngineByName("scala");

        // this is a trick I found to access the classpath,
        // might be the problem
        scala.collection.immutable.List nil = scala.collection.immutable.Nil$.MODULE$;
        scala.collection.immutable.$colon$colon<String> vals = scala.collection.immutable.$colon$colon$.MODULE$.apply("true", nil);
        (( engine).settings().usejavacp().tryToSet(vals);


And here is the output:

java.lang.Thread.getStackTrace(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)$$ReadEvalPrint.callEither(IMain.scala:777)$ReadEvalPrint.evalEither(IMain.scala:792)$WrappedRequest.eval(IMain.scala:613)
javax.script.AbstractScriptEngine.eval(Unknown Source)

java.lang.Thread.getStackTrace(Unknown Source)

The stack trace shows that the script engine ends up creating a new instance of Singleton, but I got no idea why.

Thank you.


Found out the fix after browsing the source code:

(( engine).settings().embeddedDefaults(Main.class.getClassLoader());

This changes the ClassLoader for the ScriptEngine to the same one.

Need Your Help

How can I go back to the initial view controller in Swift?

swift uinavigationcontroller pushviewcontroller

So I have a login view, after successful login it goes to the first view of a navigation controller, then the user can go deeper to a settings view and then to a logout view. This logout should tak...