In my Processing application, I listen for mouse clicks and then handle them in a button class. The button class then sets the right content via calling setScreenIndex. The function detects if this is the first time loading the screen, and then sets it up (not set up upon instantiation so unnecessary screens arent loaded if the user doesnt need them). The setting up is done via a thread that calls a setup function. This thread however seems to cut off when the mouse is clicked again whilst it is busy. This results in either the loading screen displaying indefinitely (the thread still registers as alive even though it no longer appears to do anything), or the loading screen freezing completely. I believe this is a threading issue, and somethings interacting weirdly but I am lost and have spent a week on this problem. Relevant code below:
final class Main
{
public synchronized void update()
{
try
{
if (threadToWaitFor != null)
{
if (!threadToWaitFor.isAlive())
{
threadToWaitFor = null;
setScreenIndex(nextScreenIndex);
}
}
currentScreen.update();
}
catch (Exception e)
{
logger.println("ERROR: Main Update: " + e.getMessage());
logger.println("Stack Trace: ");
e.printStackTrace(logger);
logger.flush();
exit();
}
}
public synchronized void setScreenIndex(int screenIndex)
{
this.screenIndex = screenIndex;
currentScreen = screens.get(this.screenIndex);
if (!currentScreen.getSetup())
{
SetupScreenThread thread = new SetupScreenThread(currentScreen);
thread.start();
waitForThread(thread, screenIndex);
}
}
public synchronized void waitForThread(Thread thread, int newScreenIndex)
{
this.threadToWaitFor = thread;
this.nextScreenIndex = newScreenIndex;
this.currentScreen = loadScreen;
}
}
I have tried checking the button isnt being called twice and that the same functions arent being called at the same time using the synchronised and volatile keywords, but this doesnt help. If you do not click multiple times, everything is fine and behaves/loads correctly. I have tried implementing a lock in the main class so that the click doesnt even reach the Main class if the flag is set to busy but this also doesnt work.