I'm trying to diagnose convoluted multithreading operations in java. I want to use the debug perspective to do so, but I encounter the following issue :
Expected behavior : When pausing a thread (through the Debug view), the "Variables" view should show the variables as seen by the thread I paused. Using the Step over / step into operation multiple times should not modify variables in the thread.
Code (Using java 17):
package fr.fgoux.debugbugdemo;
public class DebugDemoMain
{
public int t;
public DebugDemoMain()
{
this.t = 0;
}
public static void main(final String[] args)
{
final DebugDemoMain demo = new DebugDemoMain();
final Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{
for (int i = 0; i < 100; i++)
{
try
{
Thread.sleep(5);
} catch (final InterruptedException e)
{
e.printStackTrace();
}
demo.t++;
}
System.out.println("Write terminated");
}
});
final Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
while (demo.t != 100)
{
}
System.out.println("READ terminated");
}
});
t1.start();
t2.start();
try
{
t1.join();
t2.join();
} catch (final InterruptedException e)
{
e.printStackTrace();
}
System.out.println("END");
}
}
Behavior : When I run this in debug mode, I get the output :
Write terminated
And the other thread keeps running.
If I pause the running thread, the debugger shows me it's stuck at "while (demo.t != 100)". But the "variables" tab shows me t=100. If I resume / pause this thread, it stays at the "while (demo.t != 100)" and keeps running.
If I press a step by step button, the thread execution line jumps out of the while loop, and then If I resume execution, the thread terminates with "READ terminated".
Personnal interpretation :
The reading thread that does the "demo.t != 100" caches the variable demo.t so that it does not notice that the other thread changed demo.t value (which is expected since there is no synchronization). It cannot make progress.
The "Variables" view does not show locally cached variables of the thread, but only some global representation of the variables (maybe in the shared memory).
The step by step operations cause the thread to update it's cache from the shared memory.
Question : Is there a better debugging tool that would allow me to show these cached variables and diagnose these issues ?