Skip to Main Content

Multi-threaded code for hitting a URL a variable number of times per second

b7aAug 25 2022

Hi all,
I have written a small program for hitting a given URL a random number of times (max 100) per second, for 1 hour:

package code.b7a.stressor;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
public static void main(String[] args) {
final var someUri = URI.create("http://localhost:8080");
final var random = new Random(0xCAFEBABE);
final var corePoolSize = 2;
final var scheduledExecutorService = Executors.newScheduledThreadPool(corePoolSize);

    // stop execution after 1 hour
    scheduledExecutorService.schedule(() -> {
        scheduledExecutorService.shutdownNow();
    }, 1, TimeUnit.HOURS);

    // hit \`someUri\` a random number of times, once per second
    scheduledExecutorService.scheduleAtFixedRate(() -> {
        hitAsynchronouslyAndWait(someUri, random.nextInt(100));
    }, 0, 1, TimeUnit.SECONDS);
}

public static void hitAsynchronouslyAndWait(URI target, int concurrency) {
    final var httpClient = HttpClient.newHttpClient();
    final var request = HttpRequest.newBuilder(target).GET().build();
    final var responses = new ArrayList\<CompletableFuture\<HttpResponse\<Void>>>(concurrency);

    for (int i = 0; i \< concurrency; i++) {
        responses.add(httpClient.sendAsync(request, BodyHandlers.discarding()));
    }

    for (CompletableFuture\<HttpResponse\<Void>> resp : responses) {
        resp.join();
    }
}

}

Unfortunately my concurrent programming skills are quite weak, and I was wondering if what I have written is correct and if there are ways in which I can improve it?
Other than that, is there a rule of thumb we can follow for selecting a reasonablecorePoolSize?
Thanks in advance.

Comments
Post Details
Added on Aug 25 2022
0 comments
22 views