Question

The description for the method uptimeMillis says:

Returns milliseconds since boot, not counting time spent in deep sleep. Note: This value may get reset occasionally (before it would otherwise wrap around).

How often might this happen and (more importantly) will it affect runnables that should be executed by Handler.postAtTime?

Was it helpful?

Solution

The uptimeMillis call grounds out in systemTime(), which on a Linux system turns into clock_gettime(CLOCK_MONOTONIC, struct timespec *).

The struct timespec holds seconds in a time_t, which appears to be a 32-bit value. If it starts counting near zero, you will not likely be alive when it wraps.

If you need more specific details, you should investigate the behavior of clock_gettime(CLOCK_MONOTONIC) in the Linux kernel.

OTHER TIPS

If you happened to call uptimeMillis right when it wrapped, then yes it would affect your postAtTime call.

A signed long in Java has the range:

-9,223,372,036,854,775,807 to 9,223,372,036,854,775,807 (~9.2E18)

9.2E18 milliseconds is 292,277,266 years. If you are working on a space probe, you probably want to take this into consideration, otherwise you can probably get away with assuming it won't wrap in your lifetime.

The kicker for me is that the Android documentation for uptimeMillis claims

This clock is guaranteed to be monotonic . . .

Then soon after they say that uptimeMillis will be reset due to variable wrapping - the exact opposite of a monotonic clock!

I was using it for a service and did not ever see it resetting. I would really assume it won't. The problem with postAtTime() is that it will not be called during sleep (since uptimeMillis() will not update). If that's an issue, then I would use some other method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top