The use of System.currentTimeMillis() in loops in Java

1.5k views Asked by At

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?

2

There are 2 answers

0
Peter Lawrey On BEST ANSWER

If you are concerned about comparison between times you can use

while (System.currentTimeMillis() - start < RUN_TIME)

This could be a problem with nanoTime as it could overflow after 292 years. However, with currentTimeMillis you have about 292 million years.

1
Fahim Parkar On

Please run the above program before you sleep and see the output when you woke up in morning.. You will get your answer...