How to Handle Timeouts in Network Communication in Java?
Last Updated :
26 Feb, 2024
In Java, Timeouts in Network Communication mean when the end user sends a request to the server through a network, the server takes a lot of time to process the request and send it the in form of a response. In real-time applications we need to handle this situation for end users we need to give one error message to explain this situation like server time out, unable to process the request, request time exceeding, and other error messages.
In this article, we will learn how to Handle Timeouts in Network Communication in Java.
Approaches to Handle Timeouts in Network Communication
For handling timeouts in network communication in Java we have two different approaches.
- Using Socket Timeout
- Using Asynchronous Communication with Timeout
Program to Handle Timeouts in Network Communication in Java
Below are the code implementations of the two approaches.
Approach 1: Using Socket Timeout
In this approach, we have provided communication through socket.
- The Socket is one of the classes in Java.
- It is used for communicating with servers.
Java
import java.net.*;
public class SocketTimeoutExample
{
public static void main(String[] args)
{
try {
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress( "example.com" , 80 );
int timeout = 5000 ;
socket.connect(address, timeout);
System.err.println( "Connection Success" );
socket.close();
} catch (SocketTimeoutException e)
{
System.err.println( "Connection timed out" );
} catch (Exception e)
{
e.printStackTrace();
}
}
}
|
Output:
If you get Server response with 5 seconds, then output as below:
Connection Success
Otherwise, the response gets with time limit then you will get output as below:
Connection timed out
Explanation of the above Program:
- First, we have created one Java Class and in the main method, we have defined Socket communication by using Socket class.
- Once we connect with given host, the host send response with in 5 seconds otherwise we get time out error message.
- Else, we will get Connection success message as an output.
Approach 2: Asynchronous Communication with Timeout
This is another approach for handling timeouts in network communication in Java. Here, we have used future and ExecutorService. The future returns the future object when it is started and The ExecutorService is used for tracking the requests means completed or not.
Java
import java.net.*;
import java.util.concurrent.*;
public class AsynchronousTimeoutExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
try {
Future<Void> future = executor.submit(() -> {
try {
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress( "example.com" , 80 );
int timeout = 5000 ;
socket.connect(address, timeout);
socket.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return null ;
});
future.get( 5 , TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.err.println( "Operation timed out" );
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
|
Output:
If we get any response with 5 second, we will get time out error message.
Operation timed out
Explanation of the above Program:
- First, we have created one Java Class and in the main method we have defined Socket communication by using Socket class and future and ExecutorService.
- Once we connect with given host, the host send response with in 5 seconds otherwise we get time out error message.
- Otherwise, we will get Operation timed out message as an output.
Note: If you want to generate the output, you can compile and run this code in your local environment. You have to replace example.com
with a valid hostname or IP address of a server that you want to connect to.
Share your thoughts in the comments
Please Login to comment...