Doubt about System.currentTimeMillis()

Asked

Viewed 1,406 times

4

I was discussing with a friend now little about the origin of the number that results from this method. Where does it come from? It has been counted since when? It reset?

1 answer

4


It comes from the operating system.

The OS is loaded and picks up an initial state contained in the machine’s memory (it needs to have a battery or be on) and/or an external source (internet or other input) and takes how much time goes through each processor cycle (it itself has this information in it).

Processor increments a value in one location at each execution cycle.

The operating system may have several mechanisms to deal with this.

For example, he says he wants this information every period of time and the processor signals every few cycles (in truth we call it ticks which may not be the cycle itself) to calculate how much time has passed from that initial state. So he can increase the time spent that he controls.

It can only check when it is requested by some application (this usually occurs all the time) and calculate the time spent by adding up the initial state it obtained (which can be updated under certain circumstances) with the time spent with the ticks increased and the time it takes each of them.

There is hardware that can do this and the OS just needs to get the value ready.

Obviously if the operating system has no way of knowing the exact time when it starts this number will be wrong. There is no magic.

This period can be longer than 1 millisecond, so one can often not use this type of information to check time spent in an operation, as many people do to evaluate performance. Even with shorter times there will be discrepancy. So just use to know the current time, not for time measurements.

The number that Java takes is a timestamp which is an amount of time that has passed from a moment in the predetermined time. In this case it uses the standard adopted by Unix, so it is the initial moment of January 1, 1970 (look at you now).

If it’s all right on the machine it’s not reset.

If the control of timestamp is made with a small data may be that one day it gives some problem and may return to the initial moment of 1970, but this is a specific implementation problem.

Documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.