0

My Jython script is calling some code that I'm writing in Java (because I am more comfortable with Java multithreading). Now it turns out that I need to call one of the Jython methods from Java (otherwise I'd have to re-write it in Java).

It's easy to drive Java from Jython, and it's also straightforward to set things up such that Java is the master and Jython is the slave, but it's not as obvious what's the best way to set it up so that they could call each other.

The official documentation contains a very long article about all this: Chapter 10: Jython and Java Integration, which makes the task seem hard at first glance: one-to-one object factories, loosely-coupled factories, and a lot of code to make it work.

There are other sources I found which also go into a lot of detail, but neither offer any simple solutions:

Since there is a Jython interpreter already running, there should be a simple way to call a method in it, without having to instantiate a new interpreter (as in the last link above, and as you would need to do if Java was driving Jython). Is there actually such a way?

Community
  • 1
  • 1
Evgeni Sergeev
  • 22,495
  • 17
  • 107
  • 124

1 Answers1

0

This article suggested a simple solution, and the following example worked. Java:

import org.python.core.PyObject;

public class JythonFromJava {
    public void callPO(PyObject po) {
        po.__call__();
    }
}

Compiled with:

$ javac -classpath ".;C:\Programs\jython2_7b1\jython.jar" JythonFromJava.java

Jython:

import JythonFromJava

def method():
    print "METHOD called"

j = JythonFromJava()
j.callPO(method)

Running it:

$ jython jython_from_java_j.py 
METHOD called

So it seems that's all that's needed. We do need to send a handle to the Jython method into Java, as a kind of a callback, except in this case it's not a tool for asynchronous requests, but for inter-language requests.


EDIT: I'm not sure where that leaves us with multithreading. I'll be calling the Jython method from another thread that's created and started within the Java code, so I hope the Jython interpreter ensures synchronised access to itself...

Evgeni Sergeev
  • 22,495
  • 17
  • 107
  • 124
  • Actually, Jython is even better with multithreading than CPython https://www.jeffknupp.com/blog/2013/06/30/pythons-hardest-problem-revisited So I guess interpretation happens on each thread separately, and the only things left to worry about are the usual aspects of multithreaded programming. Also: http://www.jython.org/jythonbook/en/1.0/Concurrency.html which also says that `list`, `dict` and `set` are already synchronised. So, one less thing to worry about! – Evgeni Sergeev Apr 21 '14 at 03:03