If you're pre-1.4, I think you need to set the server socket's SoTimeout before entering your accept() loop. If you don't get a connection request, accept() returns null I guess and you can then test your boolean.
If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
I hadn't considered that you were using the main thread. I normally use Runnable instead of extending Thread as it's cleaner, expresses the intent better (I'm not altering how threads behave), and keeps me from exposing methods I don't want the clients of my class calling (interrupt for one).
Originally posted by M Beck:
so are you saying i should make the main class extend Runnable (or Thread?) and start another thread in it? or rather that i should make a singleton class extending Runnable (Thread?) and start a single thread running that?
I used to feel the same way until I read through the JLS section on threading. The thing is, each thread is allowed to put variables into registers for optimization. Since the boolean is used in a tight loop, it's quite possible that it will be cached in a register and never checked in memory again. In that case, it wouldn't pick up the changed value. Synchronizing forces it to be pulled from memory again. Another way is to mark that field volatile. Then every time it is accessed, it must be accessed directly from memory.
i thought, it's a boolean; it can only have two states, it starts out in one, and once switched to the other it can never be switched back -- so what if a couple of threads have a race condition on switching its state? it's not like they'll block on it, after all, right?
My last paragraph was actually me musing on a different way of implementing the cancellation logic -- not a concern that multiple threads would close the socket. Instead of using interrupt, I was suggesting closing the socket directly. This would kick the main thread out of its accept() state with an exception. It was just another method of achieving the same thing.
i don't think your concerns in your last paragraph apply to my situation; i'll only ever have a single thread working with the ServerSocket, so there's no way i'll end up calling accept() on it after it's closed, or try to close it while it's blocked on accept.
Hey, check out my mega multi devastator cannon. It's wicked. It makes this tiny ad look weak:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earthhttps://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter