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.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.
If I'd had more time, I would have written a shorter letter. -T.S. Eliot such a short, tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|