3

I am using a variable time_of_last_call as my origin of time; since nanoTime() might give negative values, I can’t use 0 as my origin of time to initialize time_of_last_call. If I initialize time_of_last_call with Long.MIN_VALUE I can have overflow issues. Any suggestions?

EDIT: I think I should just initialize it as:

long time_of_last_call = System.nanoTime()/1000000L;

//long time_of_last_call =Long.MIN_VALUE; //could have overflow issues
//long time_of_last_call =Long.MIN_VALUE/1000000; // could still have overflow issues?

//BEGIN OF CODE WITH A LOOP
// “time_of_last_call” may (or not) be updated: 
if (some_condition) 
    time_of_last_call=System.nanoTime()/1000000L;

if ( ( System.nanoTime()/1000000L - time_of_last_call ) > 10 )
    // do something
//END OF CODE WITH A LOOP
user20191130
  • 340
  • 1
  • 9
  • Never had an issue of negative nanotime, my guess is that you are not using it right – Steyrix Dec 09 '19 at 06:06
  • Can you please post your code, which gave you negative value of System.nanoTime()? – Steyrix Dec 09 '19 at 06:09
  • According to the javadoc it could be negative – R.Groote Dec 09 '19 at 06:11
  • Thanks guys, according to Oracle's docs, nanoTime can give negative values. Just edited my question. I think it is safe to initialize my variable as: System.nanoTime() – user20191130 Dec 09 '19 at 06:38
  • Well, initializing to `System.nanoTime()/1000000L` would be better. – Andreas Dec 09 '19 at 06:46
  • it depends of what you want/need to do, of the *meaning* of its initial value. Maybe use a `boolean` flag, or, as done, use the `nanoTime()`, Anyway the divisions by `1000000L` can be removed (assuming posted code is the whole usage of it) - compare to `10 * 1000000L` or `10_000_000L`) – user85421 Dec 09 '19 at 07:10

1 Answers1

2

As far as I know, there is no "origin" for nano time. You should only use it to find a difference between two instants in time, in which case the "origin" is irrelevant.

In addition, as far as I remember, it's not guaranteed to be consistent over VM restarts. Therefore, if you persist this value, you can run into some subtle bugs.

From the naming of your variables it looks like all you want to do is to track call times. You most probably don't need the precision and resolution of nano time for this use case, so you'll probably be better off using System.currentTimeMillis() instead.

Vasiliy
  • 16,221
  • 11
  • 71
  • 127