Why the hang() method is only getting executed for one time?

Tags: , , ,



class Demo{

    static void hang(){  // Freezes/Hangs the program for some seconds.
        for(int i=0 ; i<100000 ; i++){
            for(int j=0 ; j<10000 ; j++){
                for(int k=0 ; k<10000 ; k++){
                    int b = 5%12000;
                }
            }
        }
    }

    public static void main(String a[]){
        System.out.print("Loading");
        hang();
        for(int it=0 ; it<5 ; it++)
        {
            System.out.print(".");
            hang();
        }
    }
}

The task of hang() method is to hang/freeze the program for certain time (I know there are other ways to freeze a program, but I want to show it by using for loop). But when I am executing this, the first hang() call, below the System.out.print("Loading") is taking a certain amount of time and giving a delay, the first call in for loop is also giving delay, but the rest of the call (in the for loop) is not taking any time and getting executed instantly and no delay is seen.

Consider all hang() calls are getting called(I have checked this by writing a print statement in hang() method).

Consider int b = 5%12000 takes time each time it is called (Checked this even, by replacing it by if(True))

This same code is working in c++ i.e. it shows delay after each “.”

Output in c++ was like Loading[d].[d].[d].[d].[d].

But in Java it was like Loading[d].[d]....

[d] is delay

And if I replace the hang() call with the entire method code in hang() method, it works

class Demo{

    static void hang(){  // Freezes/Hangs the program for some seconds.
        for(int i=0 ; i<100000 ; i++){
            for(int j=0 ; j<10000 ; j++){
                for(int k=0 ; k<10000 ; k++){
                    int b = 5%12000;
                }
            }
    }

    public static void main(String a[]){
        System.out.print("Loading");
        hang();
        for(int it=0 ; it<5 ; it++)
        {
            System.out.print(".");
            for(int i=0 ; i<100000 ; i++){
                for(int j=0 ; j<10000 ; j++){
                    for(int k=0 ; k<10000 ; k++){
                        int b = 5%12000;
                    }
                }
            }
        }
    }
}

Answer

A good optimizer could figure out that hang() does nothing – it has no side-effects (apart from taking time) and produces no outputs. Therefore it optimizes to ‘nothing’.

I suspect that is what is happening.

The reason you see a couple of ‘full’ executions is that the just-in-time compiler did not immediately get turned loose on that routine.



Source: stackoverflow