[zeromq-dev] ZMQ.Poller in Java: how to do timeout check for REQ/REP?

Igor 'Lo' (И.L.) bombsiteunrested at gmail.com
Tue Sep 6 18:18:18 CEST 2011

Hi all.

I have ZMQ.REP socket sitting in some unstable C++ application, so
Java client (doing ZMQ.REQ) can occasionally hang on socket.recv(),
blocking the application.
What I want is to have a recv() timeout of two seconds, returning an
error if other party didn't either responds all all (TCP error on
connection, adopted via LINGER) or responce time is bigger than 2
seconds (have poll() to timeout after 2 seconds waiting).

Following code does not work (hangs at polling):

package TestPack;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import java.util.*;
import java.math.BigInteger;

import org.zeromq.ZMQ;
import org.msgpack.*;

class TestPack {
	private static void doTest(String tester)
		byte[] raw = MessagePack.pack(tester);

		ZMQ.Context context = ZMQ.context(1);
		ZMQ.Socket jsocket = context.socket(ZMQ.REQ);
		jsocket.connect ("tcp://localhost:1234");
		jsocket.send(raw, 0);

		ZMQ.Poller it = context.poller(1);
		it.register(jsocket, ZMQ.Poller.POLLIN);
		System.out.println("Started polling");
		boolean got = false;
		it.poll(); // <--- hangs here.
		System.out.println("Done polling");
		if (it.pollin(0)) {
		    byte[] reply = jsocket.recv(0);
		    String decode = new String(reply,0,reply.length-1);
		    got = true;
		if (got == false) {
		    System.out.println("Received nothing");

	public static void main(String[] args)
          doTest("hello world");

Following (C++) code worked ok, (don't make me use JNI for having
working poll implementation):
	zmq::pollitem_t items[] = {
		{ socket, 0, ZMQ_POLLIN, 0}

	zmq::message_t reply;
	zmq::poll(items, 1, 2*1000000); // 2 microseconds.
	std::cout << "polled" << std::endl;
	if (items[0].revents & ZMQ_POLLIN)
		std::cout << "received reply " << std::endl;
	} else {
		std::cout << "no reply" << std::endl;


More information about the zeromq-dev mailing list