Search code examples
jvmvolatilejvm-argumentsmemory-barriers

Force JVM to cache variables for threads


Is there a way to tell the JVM to cache variables for threads as long as possible and never update them unless memory barriers or volatile variables are used? (for testing)


Solution

  • It's not really a thread-local cache of variables that leads to such famous effects as the never-terminating conditional loop.
    It's more that the compiler may eliminate redundant loads if it can prove that the variable does not change/does not need to observe concurrent changes between loads.

    Many concurrency failures also don't necessarily depend on seeing stale values, they can also occur due to seeing new values out of order. I think I've read something about a modified research VM that aggressively performs legal but programmer-hostile transformations on the generated code to provoke concurrency failures.

    What you can try is bumping up all inlining limits and code cache sizes and hope that as much as possible gets compiled into a huge blob of code and the compiler eliminates as many loads as it can.