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.
start++or anything similar in your loop. Eventually you'll run out of memory I suppose.startwill always be less than the value of the value returned bySystem.currentTimeMillis()in your outer for loop's test condition. This whole pattern looks horrible, but if you insist on using it then try creating anendtime which is current time plus four seconds, and then change your for loop test condition toSystem.currentTimeMillis() < end.