Using Workers and Scripting

NeuroKernel allows running scripts in a web worker. Web worker code must be either Java or Javascript based. The java code is converted to Javascript on the fly by display server. Java support has a minimal library support. It is basically useful for processing data in the background such as images. Data can be passed to worker and received from easily using a worker adapter as seen in the code below. In this example, the code passes a value to the script and expects it to return the result as well as print them to the console. The postData method is used to post the result back to the worker handler or parent application.

import com.neurokernel.client.*;
import com.neurokernel.client.system.*;
import com.neurokernel.client.constants.ScriptLanguage;
import com.neurokernel.client.system.adapter.NWorkerAdapter;
 
public class WorkerExample extends NApplication {
    @Override
    public void main(int argc, String[] argv) {
        NFrame mainFrame=getMainFrame();
 
        new NButton(mainFrame,"Run").addListener(new NActionListener() {
            @Override
            public void onAction(NEvent e) {
                String fibonacci="public class Fibonacci {"
                        + "  public long fib(int n) {"
                        + "    if (n <= 1) return n;"
                        + "     else return fib(n-1) + fib(n-2);"
                        + "  }"
                        + "} "
                        + "public void hello(String args){"
                        + "    console.log(\"hello: \"+args);"
                        + "} "
                        + "public void main(Object[] args){"
                        + "  int n=Integer.parseInt(args[0]);"
                        + "  Fibonacci fibo=new Fibonacci();"
                        + "  for (int i = 1; i <= n; i++) {"
                        + "     System.out.println(\"worker:\"+fibo.fib(i));"
                        + "     postData(i + \": \" + fibo.fib(i));"
                        + "  }"
                        + " "
                        + "}";
 
                IWorkerHandler scripting = getSystem().getRuntime().getWorkerHandler();
                scripting.addWorker(new NWorkerAdapter() {
                    @Override
                    public void onData(Object message) {
                         getSystem().getConsole().println("Result:"+message);
                    }
                }, ScriptLanguage.JAVA, fibonacci, 20);
            }
        }
 
        mainFrame.setTitle("Worker Example");
        mainFrame.setBounds(20,20,200,200);
        mainFrame.setVisible(true);
    }
}