So this is my code that polls for a change in my app’s model.
Thread refreshThread = new Thread(new Runnable() {
public void run() {
while(true)
{
if(TasksManager.isDirty())
{
TasksManager.refreshTasks(true);
panel.repaint();
}
}
}
});
refreshThread.start();
Right now it is an immense CPU hog.
Here’s the breakdown of what happens.
- TaskManager realizes that something new has been added.
- TaskManager marks itself as dirty.
- When my refresh threads finds that its dirty, it immediately performs a refresh on the model and the display panel.
- At the end of RefreshTasks(), the model is again marked as clean.
I didn’t want the TaskManager to start the refresh since it doesn’t hold any reference to the Viewing Panel.
One idea I have is to use a condition.await(). The TaskManager can signal the condition when it has been marked as dirty. But I see that Locks and Conditions go hand in hand. Would it be okay to use a Condition without acquiring a Lock at the beginning of the function?
You can use
wait()andnotifyAll()to avoid high CPU usage: