Skip to content

Commit c32b811

Browse files
jpstotzdmsnell
authored andcommitted
Java: Use monotonic timer for comparing timeout instead of system clock. (#15)
Previously the timeout was compared against the system clock, which is prone to skew and unexpected changes. With this patch the comparison is made against `System.nanoTime()` which is a high-precision monotically increasing time designed for elapsed time measurements. This isolates the timeout from system variation.
1 parent c03ac60 commit c32b811

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
# Next version
2+
3+
## Java
4+
5+
- `Diff_Timeout` is now compared using a monotonically increasing high-resolution
6+
timer to isolate the timeout duration from clock skew. (@jpstoz)
7+
18
# 1.1.0
29

310
## Javascript

java/src/name/fraser/neil/plaintext/diff_match_patch.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ public LinkedList<Diff> diff_main(String text1, String text2,
138138
if (Diff_Timeout <= 0) {
139139
deadline = Long.MAX_VALUE;
140140
} else {
141-
deadline = System.currentTimeMillis() + (long) (Diff_Timeout * 1000);
141+
deadline = System.nanoTime() + (long) (Diff_Timeout * 1000000000l);
142142
}
143143
return diff_main(text1, text2, checklines, deadline);
144144
}
@@ -151,7 +151,7 @@ public LinkedList<Diff> diff_main(String text1, String text2,
151151
* @param checklines Speedup flag. If false, then don't run a
152152
* line-level diff first to identify the changed areas.
153153
* If true, then run a faster slightly less optimal diff.
154-
* @param deadline Time when the diff should be complete by. Used
154+
* @param deadline Time in nanoseconds when the diff should be complete by. Used
155155
* internally for recursive calls. Users should set DiffTimeout instead.
156156
* @return Linked List of Diff objects.
157157
*/
@@ -382,7 +382,7 @@ protected LinkedList<Diff> diff_bisect(String text1, String text2,
382382
int k2end = 0;
383383
for (int d = 0; d < max_d; d++) {
384384
// Bail out if deadline is reached.
385-
if (System.currentTimeMillis() > deadline) {
385+
if (System.nanoTime() > deadline) {
386386
break;
387387
}
388388

0 commit comments

Comments
 (0)