Fix issue #79 (negative duration/elapsed time) #80
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR solves the bug #79.
I could reproduce the trouble creating a
MonitoredRunnable
that executes a simple and fast runnable 1 million times (the average duration for the SYSTEM_TIME counter was 0.000002312 seconds).During the analysis, I realized that, in some (frequent) cases, the nanoseconds after the operation were populated with an amount that was lower than the value retrieved before the operation, due to a known accuracy issue inside JDK's
ThreadMXBean
.According to the JDK 17 Javadoc: "The CPU time provided is of nanoseconds precision but not necessarily nanoseconds accuracy" (https://docs.oracle.com/en/java/javase/17/docs/api/java.management/java/lang/management/ThreadMXBean.html).
So, to avoid the negative elapsed time, I implemented the following fixes:
Counter.elapsedTimeNanos()
was modified to return zero (instead of -1) when the time retrieved after the operation is lower than the one retrieved before the operationDuration
class now also allows negative amounts, to prevent the issue from happening in another situation (for example, if CPU time is not supported by the JVM)The fix was validated with JUnit and a new stress test method at the
PerformetricsTestDrive
class.✅ The fix will be released in Performetrics version 2.5.2.