Talk:CompilerOptimizations
From APIDesign
(New page: 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 fr...) |
|||
Line 7: | Line 7: | ||
} | } | ||
- | 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. | + | 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. Even here it is not necessarily the case. In general you cannot assume that a local object reference in a java method will be "cleaned up" in any way prior to the exit of the method. For example, hotspot might simply remove the "set to null" if nothing reads the variable later on. If you MUST influence the garbage collector from a method that, say, loops and dispatches events forever, you should use an AtomicReference to hold the value. This shifts the reference out into the heap and allows proper control over its value, and the propagation of that value to other threads (like the garbage collector). |
RJudson | RJudson |
Revision as of 14:53, 17 October 2008
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. Even here it is not necessarily the case. In general you cannot assume that a local object reference in a java method will be "cleaned up" in any way prior to the exit of the method. For example, hotspot might simply remove the "set to null" if nothing reads the variable later on. If you MUST influence the garbage collector from a method that, say, loops and dispatches events forever, you should use an AtomicReference to hold the value. This shifts the reference out into the heap and allows proper control over its value, and the propagation of that value to other threads (like the garbage collector).
RJudson