Question: I have written a java program in which I am supposed to know that if the two nested for loops can finish their execution in 4 seconds or not If they finish their execution in 4 seconds then the program should continue else break the loop. I have three list A ,B and C and I am performing some operation and adding it to the list B. Even for the small inputs to the list A and C like 3, 6, 8, 4, My program throws `run out of memory error`  

I am using one outer for loop for calculating time. If two for loops couldn't finish their execution in 4 seconds the loop should be terminate. I am using one count variable to keep track of the for loop execution even if for loop finished their execution before 4 seconds i am terminating the outer for loop.  

Here is my **code** :

```
while(!(A.isEmpty())){
    ArrayList<Long> B = new ArrayList<>();
    for(long start = System.currentTimeMillis() ; start < System.currentTimeMillis() + 4 * 1000 ; ){
        for(long i : A){
            for(long j : C){
                if(i!=j){
                    B.add(Math.abs(i-j));
                }
            }
            count++;
            if(count==A.size());
                break;
        }
    }
}

```

What is wrong with this code ? How should I make it correct ?  

Thank you.

Answer: 
Statement `while(!(A.isEmpty()))` will run an infinite loop causing B to be instantiated infinite times.

As a result causing OutOfMemoryError
You Have an infinite loop, `while(!(A.isEmpty))` will always be true because inside of your for loops you are never removing any elements from A. This will cause you to add an infinite amount of elements to B becuase of `B.add(Math.abs(i-j));`