Java Socket setSoTimeout() method

25 Mar 2025 | 2 min read

The setSoTimeout () method of Java Socket class enables or disables the SO_TIMEOUT option with the given timeout value, in milliseconds. The timeout value should be greater than 0 otherwise, it will throw an error.

Syntax

Parameter

The parameter 'timeout' represents a specific timeout in milliseconds.

Return

NA

Throws

SocketException - if an error is there in the underlying protocol, such as a TCP error.

Example 1

Output:

 Timeout value: 90987789 

Example 2

Output:

 Timeout value: 0 

Example 3

Output:

 Exception in thread "main" java.lang.IllegalArgumentException: timeout can't be negative	at java.net.Socket.setSoTimeout(Socket.java:1139)	at com.tpointtech.JavaSocketSetSoTimeoutExample3.main(JavaSocketSetSoTimeoutExample3.java:13) 

Example 4

Test it Now

Output:

 Exception in thread "main" java.net.SocketException: Socket is closed	at java.net.Socket.setSoTimeout(Socket.java:1137)	at com.tpointtech.JavaSocketSetSoTimeoutExample4.main(JavaSocketSetSoTimeoutExample3.java:16)