54

https://docs.oracle.com/javase/6/docs/api/java/lang/System.html#currentTimeMillis() says:

Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

It is not clear to me if I am guaranteed that this code will always print ever increasing (or the same) numbers.

while (1) { 
    System.out.println(System.currentTimeMillis() );
}
3
  • Please consider citing a more recent link.
    – trashgod
    Jun 5, 2010 at 1:05
  • 6
    FYI - the precise way to ask this question is whether currentTimeMillis is monotonic. Jun 5, 2010 at 1:31
  • 4
    Technically, it's monotonically increasing. Monotonic functions can be either increasing or decreasing. Jun 7, 2010 at 5:28

5 Answers 5

68

The short answer is no, System.currentTimeMillis() is not monotonic. It is based on system time, and hence can be subject to variation either way (forward or backward) in the case of clock adjustments (e.g. via NTP).

System.nanoTime() is monotonic, if and only if the underlying platform supports CLOCK_MONOTONIC -- see the comments on Java bug report 6458294 for a good writeup on some circumstances where this is/isn't true.

(And, as an additional anecdote, I have personally observed (several times) System.currentTimeMillis() run 'backwards', in the absence of clock adjustments, across threads -- that is, a call to that method in one thread returned a lower value than a call in another thread, even though it occurred chronologically after it in 'real-time')

If you need a monotonic source, System.nanoTime() on a platform supporting monotonicity is your best option.

5
  • +1 Informative. Would you elaborate on how you "personally observed" currentTimeMillis() to run backwards? This looks like a rather tricky business, and Heisenberg comes to mind. Did you synchronize your threads somehow? And could still observe time running backwards? Mar 5, 2013 at 2:09
  • 5
    The simple version is we had some timing jobs which stashed long start = System.currentTimeMillis(), and then fired off another thread to do the work, which itself did long end = System.currentTimeMillis() at the end, and subtracted the two. This difference was (not uncommonly) negative in the case of very short-running jobs. This confused the hell out of me until I did some research and dug into the code. :)
    – Cowan
    Mar 5, 2013 at 4:20
  • So thread #1 did long startInCallingThread = Sys.cTM() and passed that value to thread #2, which would get negative values for Sys.cTM() - startInCallingThread? Interesting. Were you perhaps running it in a virtual machine? And by absence of clock adjustments, do you mean only manual adjustments or would this also include automatic adjustments, like those caused by an ntp daemon? Mar 5, 2013 at 8:27
  • 1
    Yes, that's precisely what was happening. This was running on real hardware, and there were no NTP adjustments (we checked for that). I actually can't recall at the moment if this was on Windows or Linux - we developed on one and deployed on the other. From memory, currentTimeMillis was non-monotonic on our Linux box, so we switched to currentTimeNanos (which had recently become available) only to get bitten by the bug referenced above making THAT non-monotic on Windows. Time is hard. :)
    – Cowan
    Mar 5, 2013 at 12:48
  • 1
    System.nanoTime() should not be used to obtain wall time in nanoseconds. It's not guaranteed to be non-negative. The documentation says values returned from this method should only be used in subtraction expressions to determine elapsed time between calls. May 2, 2022 at 17:04
15

No, it will not always be >= all previous calls.

  • It might not increase every time if you call it several times in quick succession from the same thread (I know this is the = part of >=, but the behavior often surprises people).

  • If you call it several times in quick succession from multiple threads, it might do any number of things -- it could go slightly back in time across threads by a very small amount, depending on implementation and random chance.

  • Most seriously, the value might go back in time by a large amount if the user (rare) or an NTP sync (potentially common) adjusts the system clock.

9

It couldn't possibly be guaranteed to be increasing, based on the fact that the user could potentially change the system time between calls.

Besides that, it should stay increasing since it represents milliseconds since the epoch. If it were a normal "wall time", you would have to worry about time changes on leap day or on daylight savings changeover.

1
  • 1
    In fact, it is guaranteed to be periodic. About every 292,277,020 years, it will print an extremely large number followed by an extremely small number.
    – emory
    Jun 5, 2010 at 8:01
7

If you want a value which is monotonicly increasing you can do something like.

public enum Time {
    ;
    private static long lastTime;
    public synchronized static long increasingTimeMillis() {
        long now = System.currentTimeMillis();
        if (now > lastTime)
            return lastTime = now;
        return ++lastTime;
    }
}

As long as you call this less than a thousand times per second, your increasing time won't drift too far from the real time but will be unique. (This can work, even if you restart your application)

4
  • I dislike this so much, but it works with GitHub Actions; and system.nanoTime() does not
    – MrMesees
    Jan 27, 2020 at 22:11
  • 1
    @MrMesees You can also write a micro second timer this way, and using AtomicLong to avoid using a synchronized lock Feb 13, 2020 at 18:41
  • To be clear, does the atomic long move the synchronization / locking to the implementation of the setter on the instance of the long? AKA moving the furniture, but encapsulated; or are there better reasons to use it?
    – MrMesees
    Feb 16, 2020 at 18:11
  • 1
    Better late than never: @MrMesees - there's no reason to disllike this method - it's EXACTLY how Linux MONOTONIC_CLOCK works. May 2, 2022 at 16:18
1

@Mark Rushakoff is right; nanoTime() might be slightly more reliable.

Addendum: note these caveats, cited by @Steven Schlansker.

2
  • 2
    Do be aware of this though: stackoverflow.com/questions/510462/… Jun 5, 2010 at 0:50
  • 1
    System.nanoTime is not guaranteed to be non-negative. The doc says you should only use values from this method in expressions where an earlier value is subtracted from a later value to determine elapsed time. May 2, 2022 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.