Search code examples
javabytecodejitjmockitjava-bytecode-asm

JMockit: Mocked apis are getting reverted after sometime


I am using JMockit to mock System.currentMillis().
Few invocations returning mocked time but after sometime, it starts returning original time.
When I run the same after disabling the JIT, it runs perfectly fine.


Solution

  • This happens because the JIT optimizer in the JVM does not check for redefined methods (redefinition is done through a different subsystem in the JVM). So, eventually the JVM decides to optimize the code containing the call to System.currentTimeMillis(), inlining the call to the native Java method so that it starts executing the actual native method directly. At this point, the optimizer should check if currentTimeMillis() is currently redefined or not, and abandon the inlining in case it is redefined. But, unfortunately, the JDK engineers failed to account for this possibility.

    If you really need to invoke a mocked System.currentTimeMillis() too many times, the only workaround is indeed to run with -Xint (which is not such a bad idea, as it usually reduces the total execution time of the test run).