编辑:解决了自己,见下文(虽然我不确定我是否在这里偶然发现了一个错误)
使用下面简单的 hello-world request-reply 示例,在程序结束时关闭上下文失败:它只是挂起ctx.close()
或抛出以下异常:
Exception in thread "reaper-1" java.lang.NullPointerException
at zmq.Ctx.destroy_socket(Ctx.java:327)
at zmq.ZObject.destroy_socket(ZObject.java:144)
at zmq.SocketBase.check_destroy(SocketBase.java:938)
at zmq.SocketBase.start_reaping(SocketBase.java:753)
at zmq.Reaper.process_reap(Reaper.java:133)
at zmq.ZObject.process_command(ZObject.java:114)
at zmq.Reaper.in_event(Reaper.java:90)
at zmq.Poller.run(Poller.java:233)
at java.lang.Thread.run(Thread.java:724)
无论哪种方式,程序都不会停止。
这是代码(请注意,套接字都在创建它们的线程中关闭):
import org.zeromq.ZMQ;
import org.zeromq.ZContext;
public class App {
public static void main(String[] args) throws InterruptedException {
final ZContext ctx = new ZContext();
final Thread t1 = new Thread() {
@Override
public void run() {
ZMQ.Socket socket = ctx.createSocket(ZMQ.REQ);
socket.connect("inproc://test");
System.err.format("[Thread %s] socket connected%n", Thread.currentThread().getId());
socket.send("hello");
System.err.format("[Thread %s] hello sent%n", Thread.currentThread().getId());
String result = socket.recvStr();
System.err.format("[Thread %s] received response '%s'%n", Thread.currentThread()
.getId(), result);
socket.close();
System.err.format("[Thread %s] socket closed%n", Thread.currentThread().getId());
ctx.destroySocket(socket);
System.err.format("[Thread %s] socket destroyed%n", Thread.currentThread().getId());
}
};
// t1.start();
final Thread t2 = new Thread() {
@Override
public void run() {
ZMQ.Socket socket = ctx.createSocket(ZMQ.REP);
socket.setLinger(10000);
socket.bind("inproc://test");
System.err.format(" [Thread %s] socket bound%n", Thread.currentThread().getId());
String request = socket.recvStr();
assert request == "hello";
System.err.format(" [Thread %s] received request '%s'%n", Thread.currentThread()
.getId(), request);
socket.send("world");
socket.close();
System.err.format(" [Thread %s] socket closed%n", Thread.currentThread().getId());
ctx.destroySocket(socket);
System.err.format(" [Thread %s] socket destroyed%n", Thread.currentThread().getId());
}
};
t2.start();
Thread.sleep(2000);
t1.start();
System.err.println("waiting on the threads to finish...");
t1.join();
t2.join();
System.err.println("closing context...");
ctx.close();
}
}
编辑:解决了
事实证明这socket.close()
不起作用,仅此ctx.destroySocket(socket)
就足够了(它还关闭了套接字)。所以删除socket.close()
解决了这个问题。这是一个错误吗?