Testing java thread state

1 day ago 3
ARTICLE AD BOX

is there any API to programmatically test if a thread that entered wait was notified?

Java does not provide such an API.

I know I can get Thread.State.WAITING calling getState() ... but I need more details

Having been notified is not a thread state. Receiving a notification causes a transition from Thread.State.WAITING or Thread.State.TIMED_WAITING to another state, but

The new state can be either RUNNABLE or BLOCKED WAITING and TIMED_WAITING are not specific to threads in Object.wait() or Object.timedWait() -- other methods can confer those states too A thread can go back to waiting very quickly after notification, and this is relatively common with conventional usage patterns.

So, not only do you not have more details, you actually have fewer details than you seem to have thought you did.

I would like to run my testbench application and visualize how threads are notified, also to see if there is some statistics behind the notification selector.

I take you to be saying that this is the purpose of the question. As it often is, the answer is, "it's complicated". The answer depends on JVM implementation, host OS, OS configuration, how the JVM is launched, and possibly even whether you're considering platform threads or virtual threads. If you're curious about the details then far and away your best is to research the question. The practical likelihood of reverse engineering all of them by observing thread behavior is basically nil.

Though the choice of a thread to be notified is unspecified maybe there is some non-random predictor ...? first wait- first notified or round robin ...

For platform threads, this is typically controlled by the OS's scheduling policy. Under some circumstances that can provide FIFO scheduling, but determining this by reverse engineering gives you very little actionable information. It tells you about the particular environment and circumstances under which you tested, but this is very difficult to generalize.

For most intents and purposes, your best bet is to write code that is as insensitive as possible to scheduling details.

Read Entire Article