1
votes

I have a timer on daemon thread which is continuously writing data into a SocketChannel. In the main class I do not have the object reference of this socket channel, but I do have the reference of the ServerSocket to which this socket channel is connected. So I do this to close the channel.

socketChannel = serverSocket.accept();
socketChannel.close();

But there is a latency involved in the deamon thread's socket channel close. Though they both refer to the same socket channel, the timer task writes into this socket channel even after the above close() is invoked until a few milliseconds.

Kindly suggest how to ensure the close is made completed. This is an non blocking channel.

2

2 Answers

1
votes

Your code doesn't make sense. That code doesn't 'refer to the same socket channel' at all, and it therefore doesn't close it: it accepts a new one and closes that, which also doesn't make sense, at least not to the client who made that new connection and is probably expecting some service on it, not an immediate close.

You just need to arrange to have the reference to the existing channel available to the code that needs to close it. This is Programming 101, hardly a networking question at all.

0
votes

You need synchronization. Share some object between these threads. Then you can do something like this: main thread:

synchronized(object){
    socketChannel = serverSocketChannel.accept()
    socketChannel.close(). 
}

daemon thread:

synchronized(object){
    timerTask.write(socketChannel, data)
}