HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Efficiently using ZeroMQ sockets in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
efficientlyzeromqjavasocketsusing

Problem

I am working on multithreading project and I am using ZeroMQ socket to send the data as a byte array. Below is my example which works fine. I'm opting for code review to see whether it can be improved by adding a wrapper class for using ZeroMQ socket as some sort of socket manager.

public class TestDriver {
    private static final int THREADS = 5;
    private static final long DURATION_OF_RUN = 10;
    private static final ExecutorService executor = Executors.newFixedThreadPool(THREADS);

    public static void main(String[] args) {

        try {
            long startTime = System.currentTimeMillis();
            long endTime = startTime + (DURATION_OF_RUN * 60 * 1000);

            for (int i = 0; i < THREADS; i++) {
                executor.submit(new ClientTask(endTime));
            }

            // wait for termination
            executor.shutdown();

            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


And below is ClientTask class -

```
public class ClientTask implements Runnable {

private static final Random random = new Random();
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private final long endTime;

public ClientTask(long endTime) {
this.endTime = endTime;
}

@Override
public void run() {

while (System.currentTimeMillis() <= endTime) {
// does the way I am using ZeroMQ socket here is efficient?
// or we should make connection pooling of sockets using zeromq
// inside any singleton wrapper class?
ZMQ.Socket socket = SocketsManager.getInstance().getSockets();

byte[] byteArray = generateRandomStringAsBytes(20);

ZMsg req = new ZMsg();
req.add(byteArray);
req.send(socket);

socket.close();
context.term();

Solution

You're only sending one ZMsg per connection. Establishing TCP connections is generally considered to be a high-overhead operation. If done over a network, it would involve a three-way handshake to connect and a two-way handshake to disconnect. When done on localhost, the TCP protocol is still somewhat complex, even though the transmission latency is nearly small.

Compare that to this example, which reuses the same connection for multiple messages.

I can understand disconnecting if you have nothing to transmit for a while. However, if you are trying to push as many messages as possible in a tight loop, it makes no sense to make a new connection per message — it defeats the advantage of using ZeroMQ rather than raw TCP in the first place.

Context

StackExchange Code Review Q#69254, answer score: 3

Revisions (0)

No revisions yet.