Skip to main content

Posts

Showing posts from June 26, 2016

Load testing with Java: Pound on a resource with multiple threads

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) { …