Let's observe the following segment of code in Java that uses System.currentTimeMillis() in a for loop.
package loops;
final public class Main
{
public static void main(String... args)
{
final long MAX_VAL=Long.MAX_VALUE;
final long CURRENT_MILLIS=System.currentTimeMillis();
System.out.println("MAX_VAL = "+MAX_VAL);
System.out.println("CURRENT_MILLIS = "+CURRENT_MILLIS);
for(long time = 0; time < CURRENT_MILLIS; time++)
{
System.out.println("inside for = "+time);
}
}
}
In the above code, the final long type variable CURRENT_MILLIS holds the current millisecond maintained by the system which is always less than (MAX_VAL) the size of the long data type in Java though the for loop gets stuck into an infinite loop. How?
If you are concerned about comparison between times you can use
This could be a problem with nanoTime as it could overflow after 292 years. However, with currentTimeMillis you have about 292 million years.