Load testing involves multiple threads or processes performing operations against a resource. For example, execute a query against a database server via 50 concurrent threads. The tricky part is waiting for the threads to start up before the commands are actually executed, in order to make sure that the resource is truly getting hammered. Here's an example of how to accomplish this in Java. It is possible to refactor the following code into a utility accepts two parameters: the number of threads and a lambda expression which can be passed as a Runnable object.
final int numThreads = 50;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
CountDownLatch ready = new CountDownLatch(numThreads);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(numThreads);
for (int j = 0 ; j < numThreads ; j++) {
executor.execute(() -> {
ready.countDown();
try {
start.await();
// do something here ...
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} finally {
done.countDown();
}
});
}
// wait until everybody is ready
ready.await();
// start
// start
start.countDown();
// wait until everybody is done
done.await();
// clean up the thread pool
// clean up the thread pool
executor.shutdownNow();
executor.awaitTermination();
Comments