Reputation: 85
My program is a Java game which involves taking turns between the user and AI. Therefore after all operations are complete I have a infinite while loop which only breaks after the turn has changed. I only use an infinite loop because I am using a timer and cannot predict when the user ends their turn. But I notice that my program slows down over time to a point where even clicking buttons has no effect. Is it my loop which is causing this? Help would be appreciated.
while(true) {
if(playerTurn % 2 == 1) {
artificialIntelligence();
break;
}
}
Upvotes: 1
Views: 105
Reputation: 1552
If you use an infinite loop(while loop in your case) this operation would be performed continuously; thus slowing your application. Hence, I would suggest breaking the code into two threads.
First thread - Check user-turn event.
Second thread - Do the AI stuff.
As soon as the user event occurs, stop the thread and do what's needed. This way your code would never be blocked at any point of time; thus resulting in better performance.
Upvotes: 1
Reputation: 106
Without more code, it is hard to determine what is the real cause of the problem. However, one suspect may be that you're holding on to object references and they're not being reclaimed by garbage collection. Try using a java profiler, it can help you to pin point where exactly the issue may arise.
Upvotes: 1