testing multithreaded code in Java

Siddharth Jain siddhsql at gmail.com
Wed Sep 27 01:51:55 UTC 2023


Hello,

Is there any good way to simulate the edge cases one wants to reproduce
while testing multi-threaded code in Java? Say I have a method foo that I
want to test and make sure is threadsafe.

e.g. let's say I have a foo that has something like this in it:

var store = this.cache.putIfAbsent(documentId, EMPTY);
if (store == null) {
store = new SomeCLass(documentId);
this.cache.put(documentId, store);
} else if (store == EMPTY) {
throw new ConcurrencyException();
}

and I want to verify if two threads call foo with same documentId then 1
will succeed and the other will get an exception. This will happen most
likely in above code but is not guaranteed depending on the timing (race
conditions).

If one just lets multiple threads execute foo, then how the threads step on
individual instructions in foo is undefined and I might not be able to hit
all the cases. Is there any way to have fine-grained control to be able to
reproduce all the scenarios one wants to test? If not, what is the
best-practice to make sure a class or method is threadsafe? thanks,

S.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/jdk-dev/attachments/20230926/d16de2b5/attachment.htm>


More information about the jdk-dev mailing list