testcontainers-java icon indicating copy to clipboard operation
testcontainers-java copied to clipboard

Avoid usage of the non monotonic clock System.currentTimeMillis() in favor of System.nanoTime()

Open Nateckert opened this issue 2 years ago • 2 comments

In Java, System.currentTimeMillis() is a non-monotonic clock, which means that

long start = System.currentTimeMillis();
...
long end = System.currentTimeMillis();

System.println.out(end - start);

might print a number smaller than zero !

This is due to the fact that the internal clock of computer if not accurate and it is put back on the "right" time thanks to the UDP protocol.

Additional read: https://superuser.com/questions/759730/how-much-clock-drift-is-considered-normal-for-a-non-networked-windows-7-pc

Instead, System.nanoTime() should be prefer for timing purpose, as it will guarantee that two successive calls to it are greater than zero

Nateckert avatar Jan 04 '23 17:01 Nateckert

The comment https://github.com/testcontainers/testcontainers-java/pull/6392/files#diff-1cb71d0ebd85bd607c3da0c4e693f353e5d0b9c947a2396ffc32042f3ccbb63eL45 is now incorrect, but a good estimate is hard to guess

Nateckert avatar Jan 04 '23 17:01 Nateckert

Thanks for providing a PR @Nateckert. Is this an issue you have observed in your system while using Testcontainers?

Could you please run ./gradlew :database-commons:spotlessApply to fix the failing CI job?

kiview avatar Jan 05 '23 06:01 kiview

Thanks for providing a PR @Nateckert. Is this an issue you have observed in your system while using Testcontainers?

Could you please run ./gradlew :database-commons:spotlessApply to fix the failing CI job?

I ran the formatter.

I actually don't know if we encounter that issue, but we are currently trying to sanitize our CI and this was a quick fix to a unlikely problem that can be almost impossible to debug (looks random, there is no associated logs, ...), so that's why I wanted to contribute

Nateckert avatar Jan 06 '23 20:01 Nateckert

The comment https://github.com/testcontainers/testcontainers-java/pull/6392/files#diff-1cb71d0ebd85bd607c3da0c4e693f353e5d0b9c947a2396ffc32042f3ccbb63eL45 is now incorrect, but a good estimate is hard to guess

With the changes after @jtnord's feedback, I managed to update the estimate

Nateckert avatar Feb 03 '23 15:02 Nateckert

Thanks for your contribution, @Nateckert !

eddumelendez avatar Mar 14 '24 23:03 eddumelendez