This looks looks like an issue of communication between several threads. From the code I guess that your while(isOpen)
loop runs in a different thread than the closeServerSocket()
method of your class. To verify this add Thread.currentThread()
to your print statements.
If this is the case, you can remedy the situation by declaring isOpen
to be volatile
. Without the volatile
it is not guaranteed, if and when any other thread will see the written value. With the volatile
it is guaranteed that (my interpretation of happens-before) a thread accessing the variable later (according to wall clock time) will see the changed value.
Instead of volatile
you may prefer an AtomicBoolean
.