Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one implement a timeout in blocking mode NIO?

I'm not using any selectors or anything like that. I just have a simple ServerSocketChannel listening and a SocketChannel connecting to it in blocking mode. I want to impose a timeout on the connection, but SocketChannel.socket().setSoTimeout() does not work.

I tried making a background thread sleep for 30 seconds and checking if a variable is still null (since it will block waiting to read into that variable) but I couldn't synchronize the variable properly in that I could not access the local variable in my anonymous class.

Are there other ways to accomplish this?

Update: I've worded my question wrong. I also want to have a timeout on read operations as well as the connection itself.

like image 607
ldam Avatar asked Jun 27 '26 03:06

ldam


1 Answers

setSoTimeout() sets a read timeout, not a connect timeout, and for some reason it doesn't work at all on SocketChannels, even in blocking mode, and even with wrapped streams.

The method you are looking for is channel.socket().connect() with two arguments.

like image 76
user207421 Avatar answered Jun 29 '26 07:06

user207421