首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >中的Py4J回调

中的Py4J回调
EN

Stack Overflow用户
提问于 2017-12-02 11:33:01
回答 1查看 1.6K关注 0票数 3

我目前正尝试使用Py4J执行以下操作:

  • 在Python中定义一个方法("executor"),它调用JVM方法
  • 定义实现JVM接口的Python (“回调”)对象
  • 构造一个JVM对象,给出这个回调对象
  • 调用该对象上的一个方法,该方法将在Java中生成一个新线程,调用回调对象上的回调,回调对象将(在Python方面)执行"executor“方法

下面是我在Java方面的内容:

代码语言:javascript
复制
package javabridge.test;
public interface PythonCallback {
    Object notify(Object source);
}
代码语言:javascript
复制
package javabridge.test;
public class ScheduledRunnable implements Runnable {
    private PythonCallback callback;
    public ScheduledRunnable(PythonCallback callback) {
        this.callback = callback;
    }
    @Override
    public void run() {
        System.out.println("[ScheduledRunnable] run -> notify");
        this.callback.notify(this);
    }
}
代码语言:javascript
复制
package javabridge.test;
import py4j.GatewayServer;
public class Test {
    private PythonCallback callback;
    public Test(PythonCallback callback) {
        this.callback = callback;
    }
    public void runSynchronous() {
        System.out.println("[runSynchronous] run -> notify");
        this.callback.notify(this);
    }
    public void runAsynchronous() {
        System.out.println("[runAsynchronous] run -> spawn thread");
        ScheduledRunnable runnable = new ScheduledRunnable(callback);
        Thread t = new Thread(runnable);
        t.start();
    }
    public static void main(String[] args) {
        GatewayServer server = new GatewayServer();
        server.start(true);
    }   
}

在Python方面,我有以下脚本:

代码语言:javascript
复制
from py4j.java_gateway import JavaGateway, java_import, get_field, CallbackServerParameters
from py4j.clientserver import ClientServer, JavaParameters, PythonParameters

gateway = JavaGateway(callback_server_parameters=CallbackServerParameters())
#gateway = ClientServer(java_parameters=JavaParameters(), python_parameters=PythonParameters())

java_import(gateway.jvm, 'javabridge.test.*')

class PythonCallbackImpl(object):
    def __init__(self, execfunc):
        self.execfunc = execfunc
    def notify(self, obj):
        print('[PythonCallbackImpl] notified from Java')
        self.execfunc()
        return 'dummy return value'
    class Java:
        implements = ["javabridge.test.PythonCallback"]

def simple_fun():
    print('[simple_fun] called')
    gateway.jvm.System.out.println("[simple_fun] Hello from python!")

# Test 1: Without threading
input('Ready to begin test 1')
python_callback = PythonCallbackImpl(simple_fun)
nothread_executor = gateway.jvm.Test(python_callback)
nothread_executor.runSynchronous()

# Test 2: With threading
input('Ready to begin test 2')
python_callback = PythonCallbackImpl(simple_fun)
nothread_executor = gateway.jvm.Test(python_callback)
nothread_executor.runAsynchronous()

gateway.shutdown()

下面是执行此脚本时发生的情况。首先,使用gateway = ClientServer(java_parameters=JavaParameters(), python_parameters=PythonParameters()),两个测试都失败了:

代码语言:javascript
复制
Test 1:

py4j.protocol.Py4JJavaError: An error occurred while calling o0.runSynchronous.
: py4j.Py4JException: Command Part is Empty or is the End of Command Part
        at py4j.Protocol.getObject(Protocol.java:277)
        at py4j.Protocol.getReturnValue(Protocol.java:458)

Test 2:

Exception in thread "Thread-4" py4j.Py4JException: Error while obtaining a new communication channel
        at py4j.CallbackClient.getConnectionLock(CallbackClient.java:218)
        at py4j.CallbackClient.sendCommand(CallbackClient.java:337)
        at py4j.CallbackClient.sendCommand(CallbackClient.java:316)

但是,如果我注释掉了self.execfunc()行,那么测试1确实可以工作,而不会引发错误。然而,测试2仍然失败:

代码语言:javascript
复制
Exception in thread "Thread-5" py4j.Py4JException: Error while sending a command.
        at py4j.CallbackClient.sendCommand(CallbackClient.java:357)
        at py4j.CallbackClient.sendCommand(CallbackClient.java:316)

现在切换到gateway = JavaGateway(callback_server_parameters=CallbackServerParameters())。当我将self.execfunc()注释掉时,测试2仍然在这里失败:

代码语言:javascript
复制
Exception in thread "Thread-5" py4j.Py4JException: Error while sending a command.
        at py4j.CallbackClient.sendCommand(CallbackClient.java:357)
        at py4j.CallbackClient.sendCommand(CallbackClient.java:316)

但是至少在启用self.execfunc()的情况下,测试1确实可以工作。

我的问题是:如何使用self.execfunc()调用的线程方法?这与Py4J是可能的吗?

编辑:为了使事情更加棘手,self.execfunc()调用的Java命令应该在调用.notify()的同一个Java线程中运行。

EN

回答 1

Stack Overflow用户

发布于 2017-12-03 20:24:01

解决了。结果很简单:

  1. 在Python端使用ClientServer,在Java端也使用!
  2. 不要调用gateway.shutdown(),因为这将在接收回调之前断开Python的连接(duh!)

然后Java将灵活地遵循预期的线程模型,即接收Python回调调用的Java命令在执行回调的同一个Java线程中执行。

通过一个简单的Python函数,可以添加一个shutdown_when_done方法,该方法在退出之前等待所有回调返回。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47607463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档