testing multithreaded code in Java
Pavel Rappo
pavel.rappo at oracle.com
Thu Sep 28 15:42:52 UTC 2023
>From https://mail.openjdk.org/mailman/listinfo/jdk-dev:
This list is for the discussion of general technical issues related to the development of the current JDK main-line feature release. Please use a more narrowly-focused list (e.g., core-libs-dev or hotspot-dev) if appropriate. Discussion of general technical issues related to the development of updates of past releases (e.g., JDK 17, JDK 21) should take place on the jdk-updates-dev list.
---
You can try to re-ask your question on core-libs-dev or maybe even serviceability-dev. Sadly, you cannot ask it on concurrency-interest, because it is currently out of order (no concurrency pun intended).
-Pavel
> On 27 Sep 2023, at 04:51, Siddharth Jain <siddhsql at gmail.com> wrote:
>
> 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.
More information about the jdk-dev
mailing list