multiple thread test cases in java
- 1 minutes read - 187 wordsSome of my day job lately has been trying to get a better handle on threads in Java. In particular, we had a really weird race condition resulting from multiple threads processing an input data stream and causing some unexpected conflicts in our data access layer.
To try to replicate the problem in tests, I started with something like this:
private static Runnable runWithDelay(String name, long millis) {
return () -> {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(name + " finished");
};
}
This is just a Runnable
that waits a while, and then prints that it finished.
Then we can test with something like:
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thread(runWithDelay("r0", 200));
Thread t1 = new Thread(runWithDelay("r1", 300));
Thread t2 = new Thread(runWithDelay("r2", 100));
t0.start(); t1.start(); t2.start();
t0.join(); t1.join(); t2.join();
System.out.println("Completely finished");
}
which outputs
r2 finished
r0 finished
r1 finished
Completely finished
as we’d probably expect.
This isn’t a very sophisticated use of threads, but it was actually already enough to reproduce our concurrency bug pretty reliably in a local development environment!