Talk:CompilerOptimizations
From APIDesign
The JVM's threading and synchronization specification is extremely clear and exhaustive for this kind of thing. Remember that the garbage collector runs in one or more threads, separate from the thread of execution in your test program. Changes made within your test program follow JVM rules for when those changes are made visible to other threads. You have no synchronization mechanism in place, so according to the specification changes you are making need not be visible to the garbage collector.
In particular, the returned string value doesn't necessarily have to have a stack or register location, or even be retained at all. In this case you set the value to null, but hotspot can (correctly) note that the change need not be propagated to any other thread immediately, or even at all.
synchronized (this) {
value = null;
}
Using a block like this will force thread changes to be published; when the sync block is exited changes are "published" to other threads, as necessary.
RJudson