Как разблокировать поток, заблокированный на ServerSocket.accept ()?

Вот хорошее краткое изложение стека с открытым исходным кодом для генерации Веб-карт от одного из основателей EveryBlock.com: http://www.alistapart.com/articles/takecontrolofyourmaps

6
задан Greg Mattes 20 April 2010 в 16:23
поделиться

3 ответа

I try to design my code so that it can be "shutdown" with an interrupt. Mainly, this is because the Executor framework in Java's concurrency package uses interrupt to cancel running tasks. Also, the "shutdown" task doesn't have to know any internals of the task being killed.

However, a call to accept will not respond to an interrupt unless it is created from a ServerSocketChannel. A server created with a ServerSocket constructor will ignore interrupts, and I haven't found a way to reconfigure this.

If you can't change the code that creates the server, arrange for another thread to call close on the server socket. This will also raise an exception in thread blocked on accept, regardless of the method used to create the server socket.

This turns out to be a really big pain when using SSL. A JSSE socket is not created from an InterruptibleChannel, and won't respond to a simple interrupt on the thread.


I just noticed that the question says that the server can't be closed without notifying the client. Successfully interrupting a socket results in its closure.

On a call to accept this shouldn't be a problem, since the client is not connected if the server socket is blocked in accept. That should only be an issue for Socket instances, that represent current connections.

If that doesn't satisfy the notification requirements, a rework to use NIO's ServerSocketChannel in non-blocking mode may be necessary.

4
ответ дан 10 December 2019 в 02:50
поделиться

You should be able to close the socket from another thread.

2
ответ дан 10 December 2019 в 02:50
поделиться

Have you tried Thread.interrupt() ?

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.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

0
ответ дан 10 December 2019 в 02:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: