Providing Java non-blocking load generator with HdrHistogram
I'm creating a Java example using NIO Selector (epoll on Linux) to open 1000 concurrent connections that send HTTP HEAD requests in a loop, measuring latency from request send to receipt of full response headers identified by double CRLF. It records latencies using HdrHistogram to report the 99th percentile, demonstrating raw non-blocking sockets with accurate latency distribution for benchmarking a web server.
Here is a minimal Java NIO load generator that uses non‑blocking sockets and a single Selector (backed by epoll on Linux) to keep 1 000 connections open, send HTTP requests in a loop, and record end‑to‑end latencies into an HdrHistogram so you can inspect the 99th percentile:
import org.HdrHistogram.Histogram;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
public class NonBlockingHttpLoadGen {
static class ConnState {
final SocketChannel ch;
final ByteBuffer readBuf = ByteBuffer.allocate(8192);
boolean inFlight = false;
long sendTimeNanos = 0L;
ConnState(SocketChannel ch) {
this.ch = ch;
}
}
private static ByteBuffer makeRequest(String host) {
// HEAD avoids having to parse a body; you can switch to GET if needed.
String req = "HEAD / HTTP/1.1\r\nHost: " + host + "\r\nConnection: keep-alive\r\n\r\n";
return ByteBuffer.wrap(req.getBytes());
}
private static boolean headerComplete(ByteBuffer buf) {
int pos = buf.position();
if (pos < 4) return false;
byte[] a = buf.array();
for (int i = 3; i < pos; i++) {
if (a[i - 3] == '\r' && a[i - 2] == '\n' && a[i - 1] == '\r' && a[i] == '\n') {
return true;
}
}
return false;
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: java NonBlockingHttpLoadGen <host> <port>");
System.exit(1);
}
String host = args[0];
int port = Integer.parseInt(args[1]);
int connections = 1000;
Selector selector = Selector.open();
for (int i = 0; i < connections; i++) {
SocketChannel ch = SocketChannel.open();
ch.configureBlocking(false);
ch.connect(new InetSocketAddress(host, port));
ConnState state = new ConnState(ch);
ch.register(selector, SelectionKey.OP_CONNECT, state);
}
// Track latencies between sending request and seeing end of headers.
Histogram hist = new Histogram(3_600_000_000L, 3); // up to 1h in ns, 3 sig figs
long runUntil = System.nanoTime() + 30_000_000_000L; // run for 30 seconds
while (System.nanoTime() < runUntil && !selector.keys().isEmpty()) {
selector.select(100);
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
ConnState state = (ConnState) key.attachment();
SocketChannel ch = (SocketChannel) key.channel();
try {
if (key.isConnectable()) {
if (ch.finishConnect()) {
key.interestOps(SelectionKey.OP_WRITE);
}
}
if (key.isWritable()) {
if (!state.inFlight) {
ByteBuffer req = makeRequest(host);
while (req.hasRemaining()) {
ch.write(req);
}
state.sendTimeNanos = System.nanoTime();
state.inFlight = true;
key.interestOps(SelectionKey.OP_READ);
}
}
if (key.isReadable()) {
int read = ch.read(state.readBuf);
if (read == -1) {
// server closed connection
key.cancel();
ch.close();
continue;
}
if (headerComplete(state.readBuf)) {
long latency = System.nanoTime() - state.sendTimeNanos;
hist.recordValue(latency);
state.readBuf.clear();
state.inFlight = false;
key.interestOps(SelectionKey.OP_WRITE);
}
}
} catch (IOException e) {
key.cancel();
ch.close();
}
}
}
System.out.printf("Total requests: %d%n", hist.getTotalCount());
System.out.printf("Mean latency: %.3f ms%n", hist.getMean() / 1_000_000.0);
System.out.printf("99th percentile: %.3f ms%n", hist.getValueAtPercentile(99.0) / 1_000_000.0);
System.out.printf("99.9th percentile: %.3f ms%n", hist.getValueAtPercentile(99.9) / 1_000_000.0);
}
}
Notes:
- Build with Maven/Gradle and include
org.hdrhistogram:HdrHistogram as a dependency.
- This example issues a
HEAD / request so that the end of the response can be detected by the end of headers (\r\n\r\n). If you use GET, you’ll need to parse Content-Length and read the body fully.
- The selector interest ops are toggled between
OP_WRITE (send next request) and OP_READ (wait for response). Each connection has one outstanding request at a time; it loops as soon as a response is seen.
- Adjust
connections, run duration, and request payload to match your target load.