zeromq / jzmq

Java binding for ZeroMQ
http://www.zeromq.org
GNU General Public License v3.0
590 stars 364 forks source link

Excessive CPU usage when polling #407

Closed anhldbk closed 8 years ago

anhldbk commented 8 years ago

I used polling mechanism in the following way:

socket = context.socket(ZMQ.REQ);
socket.setLinger(0);
poller.register(socket, ZMQ.Poller.POLLIN);
socket.connect("tcp://127.0.0.1:9630");

while(true){

    poller.poll(1000); // 1s time out
    if (!poller.pollin(0)) {
        socket.close();
        poller.unregister(socket);
        socket = null;
        throw new IOException("Can NOT get any response from Linguisor");
    }

    buffer = socket.recv();
    if (buffer == null) {
        throw new IOException("Can NOT get any response from Linguisor");
    }

    // ...
}

At first, there's nothing to notice. But the more the time it run, the more CPU usage.

I decided to use socket.setReceiveTimeOut() instead. And the problem's gone (the code's below)

socket = context.socket(ZMQ.REQ);
socket.setLinger(0);
socket.setReceiveTimeOut(1000); // 1s
socket.setSendTimeOut(1000); // 1s
socket.connect("tcp://127.0.0.1:9630");

while(true){
    buffer = socket.recv();
    if (buffer == null) {
        throw new IOException("Can NOT get any response from Linguisor");
    }

    // ...
}

Could you pls explain this problem?

anhldbk commented 8 years ago

Sorry! I've got the answer from zguide: But our broker has to be nonblocking. Obviously, we can use zmq_poll() to wait for activity on either socket, but we can't use REP and REQ.