HOWTO · Java
How to Fix Java.Net.SocketTimeoutException: Connection Timed Out
In today's article, we will discuss java.net.SocketTimeoutException: Connection timed out.
On this page
java.net.SocketTimeoutException: Connection timed out means a network operation did not finish within the time allowed for it. If it occurs while opening a client connection, check the target host, port, route, listener, and configured timeout. The message alone does not identify which of those is responsible. Java or the underlying network stack may report a connection failure using a different exception type or message, so diagnose the operation and endpoint as well as the text.
What java.net.SocketTimeoutException: Connection timed out means
A TCP socket identifies one endpoint of a connection between applications. A client uses java.net.Socket to connect to a server’s java.net.ServerSocket; the server accepts the connection and receives a separate socket for communicating with that client. The timeout limits how long the relevant operation waits. It does not repair a route or make an unavailable service reachable.
When a client calls Socket.connect(SocketAddress, timeout), a positive timeout in milliseconds bounds the connection attempt. If it expires before the connection completes, Java reports a timeout. This setting is different from a socket read timeout: a connection can succeed and a later read can still wait too long for data.
Distinguish connection timeouts from read and accept timeouts
Choose the setting based on where execution is waiting:
- A connection timeout applies while a client establishes an outbound connection. Use
Socket.connectwith a timeout. - A read timeout applies while a connected socket waits for incoming data. Set it with
Socket.setSoTimeout; it does not limit connection establishment. - An accept timeout applies while a server waits for an incoming client. Set it with
ServerSocket.setSoTimeout; it does not time out a client’s outbound connection.
These limits are independent. Configure each operation that must be bounded, and choose values that fit the expected network and service latency. A timeout of zero means an infinite wait for these socket APIs, so do not use zero when the goal is a finite limit.
Common causes and how to diagnose them
Treat likely causes as hypotheses and test them from the machine and network where the Java process runs:
- The timeout is too short. Compare it with normal connection latency and the application’s latency budget. Increase it only if slow but successful connections are expected; a larger limit also makes failures take longer to surface.
- The host or port is wrong, or no service is listening. Confirm the configured hostname, resolved address, port, and server listener. Check that the service is bound to an address reachable by the client.
- The route is unavailable. Check DNS resolution and network routing from the client environment, including container or cloud network configuration when applicable.
- A firewall or remote policy filters traffic. Compare access from the same client network with access from an allowed network, and inspect relevant firewall rules or service logs.
- The server is slow, down, or overloaded. Check its health and logs around the attempted connection. A connection timeout does not prove that the server is healthy or that the timeout is the only problem.
A refused connection and a timed-out connection can point to different network outcomes, but messages vary by operating system and network path. Record the destination, operation, elapsed time, configured timeout, and original exception details before changing settings.
Set a connection timeout for a client socket
Create an unconnected Socket, then call Socket.connect with the destination and a positive finite timeout. For example, the essential calls are Socket client = new Socket(); and client.connect(new InetSocketAddress(host, port), 5000);. Put the socket in try-with-resources so it closes after use, and retain the host and port in diagnostic logs.
Run this self-contained example to see a client connect to a local server on an ephemeral port. It uses a one-second connection limit; the server accepts one client, and both sockets close when the block ends.
import java.net.ServerSocket;
import java.net.Socket;
public class LocalConnect {
public static void main(String[] args) throws Throwable {
try (ServerSocket server = new ServerSocket(0)) {
Thread worker = new Thread(() -> {
try {
server.accept().close();
} catch (Throwable ignored) {
}
});
worker.start();
try (Socket client = new Socket()) {
client.connect(new java.net.InetSocketAddress("127.0.0.1", server.getLocalPort()), 1000);
System.out.println("Connected to local server");
}
worker.join();
}
}
}
Connected to local server
The supplied run completed with exit code 0 and printed the line shown. This local success demonstrates the API pattern; it does not prove reachability of a remote production host.
Set an accept timeout on a server socket
Call ServerSocket.setSoTimeout with a positive number of milliseconds before calling accept(). For example, server.setSoTimeout(10000); limits how long server.accept() waits for a client. If no client arrives within that interval, the waiting accept operation ends with SocketTimeoutException; the server socket itself remains usable, so a server loop can catch the timeout and continue or report an idle period. Close the accepted client socket and the listening server socket when finished. This setting does not control how long the accepted connection can remain open or how long reads on it may wait.
This standalone example deliberately has no connecting client. It shows the accept deadline expiring and checks that the listening socket remains open afterward.
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
public class AcceptDeadline {
public static void main(String[] args) throws Exception {
try (ServerSocket server = new ServerSocket(0)) {
server.setSoTimeout(100);
try {
server.accept();
System.out.println("Unexpected client connection");
} catch (SocketTimeoutException timeout) {
System.out.println("Accept deadline reached");
}
System.out.println("Listening socket open: " + !server.isClosed());
}
}
}
Accept deadline reached
Listening socket open: true
The supplied run completed with exit code 0 and printed the two lines shown.
Set timeouts for HttpURLConnection
For a URL connection opened as HttpURLConnection, call HttpURLConnection.setConnectTimeout to bound establishing the connection and setReadTimeout to bound waiting for response data. For example, after casting url.openConnection() to HttpURLConnection, use connection.setConnectTimeout(8000); and connection.setReadTimeout(10000); before connecting or reading. These values are milliseconds; zero means no timeout. Read the response and close its stream with try-with-resources, then call disconnect() when the request is complete. Catch SocketTimeoutException for timeout-specific handling and other IOException failures for broader network errors. The class name is exactly HttpURLConnection.
Handle SocketTimeoutException and verify the fix
Catch SocketTimeoutException around the operation that can time out, and log useful context such as the host, port, operation, configured limit, and elapsed time. Do not silently retry forever: use a bounded retry policy only when repeating the operation is safe, and keep each attempt within the overall request deadline. Close sockets and streams in finally blocks or try-with-resources so a failed attempt does not leak resources.
After a change, verify it from the same runtime environment that failed. Confirm the address and port, check that the server is listening and reachable, and exercise the specific operation: connection establishment, read, or accept. Compare the measured duration with the configured limit and inspect server-side logs. If a larger timeout only delays the same failure, restore an appropriate limit and investigate routing, filtering, listener state, or service health instead. A successful test against a local server does not establish that a remote endpoint or production network is reachable.