Search code examples
javamultithreadingif-statementboolean-logicsystem.out

System.out.println Line Affecting Execution of the Logic


I have run into an incredibly strange phenomenon. I am currently programming an instant messenger program in Java and I have a variable to represent whether a new user has connected (this is of in a separate class). Here is the code in question where the object ListenerThread extends Thread :

boolean listenerThreadConnected = ServerDriver.getListenerThread().connected;
System.out.println("Whatever in here");
if(listenerThreadConnected){
    ...
    System.out.println("In the if statement");
    ...
}

So, this code works. When listenerThreadConnected = true the if statement executes and it outputs In the if statement and does all of the other stuff in the if statement. However, I changed no other code other than commenting out the System.out.println("Whatever in here") and the if statement didn't trigger and there was no sign of the In the if statement being outputted. My code looked like this:

boolean listenerThreadConnected = ServerDriver.getListenerThread().connected;
//System.out.println("Whatever in here");
if(listenerThreadConnected){
    ...
    System.out.println("In the if statement");
    ...
}

I am quite perplexed. How could this System.out.println affect the actual logic? I know this question is very open-ended, but have you ever had a similar experience? For some context, this is all in a while loop and ListenerThread is a concurrently running Thread. I can't seem to replicate this result except in my current code.

[EDIT] Replacing the System.out.println with a Thread.sleep(1) also seems to work, so this leads me to think that it is a concurrency issue.


Solution

  • Not so extrange at all, you are for sure in a multi thread system and your app is getting an outdated boolean value, you need to ensure memory visibility when reading the variable listenerThreadConnected

    How:?

    Declare this boolean listenerThreadConnected as volatile and the error must be gone!