Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a timeout for a InputStream's read() function?

Tags:

java

io

I have a DataInputStream that I obtained from a Socket. Is there any way I can set a timeout for dis.read(...)? Currently I spawn a new thread to do the read. While the parent thread does a thread.join(timeout) to wait before interrupting it. I am aware of nio, but I don't think I want to refactor that much at this point. Thanks.

like image 804
Zombies Avatar asked Apr 14 '10 14:04

Zombies


People also ask

Is it possible to read from a InputStream with a timeout?

It's meaningless for it to have available data. Hence, javadoc for available() also states: The available method for class InputStream always returns 0.

How to set read timeout in JAVA?

Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket. setSoTimeout(10*1000);


1 Answers

Not on the InputStream generally, but you can use Socket#setSoTimeout(int) to set a timeout for all read operations on the socket itself.

like image 88
jarnbjo Avatar answered Oct 23 '22 01:10

jarnbjo