Open In App

How to Handle Timeouts in Network Communication in Java?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java program to handle Timeouts in Network
// Communication using Socket Timeout
import java.net.*;
  
// Driver Class
public class SocketTimeoutExample 
{
      // Main Function
    public static void main(String[] args) 
    {
        try {
            // Create a new socket
            Socket socket = new Socket();
  
            // Define the address and port
            SocketAddress address = new InetSocketAddress("example.com", 80);
  
            // Define the timeout in milliseconds
            int timeout = 5000
  
            // Connect the socket to the address with the defined timeout
            socket.connect(address, timeout);
  
            System.err.println("Connection Success");
  
            // Close the socket
            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




// Java program to handle Timeouts in 
// Network Communication using asynchronous
// Communication with Timeout
import java.net.*;
import java.util.concurrent.*;
  
// Driver Class
public class AsynchronousTimeoutExample {
       // Main Function
    public static void main(String[] args) {
        // Create a new ExecutorService with a cached thread pool
        ExecutorService executor = Executors.newCachedThreadPool();
  
        try {
            // Submit a new task to the executor
            Future<Void> future = executor.submit(() -> {
                try {
                    // Create a new socket
                    Socket socket = new Socket();
  
                    // Define the address and port
                    SocketAddress address = new InetSocketAddress("example.com", 80);
  
                    // Define the timeout in milliseconds
                    int timeout = 5000;
  
                    // Connect the socket to the address with the defined timeout
                    socket.connect(address, timeout);
  
                    // Close the socket
                    socket.close(); 
                } catch (Exception e) {
                    // Throw a new runtime exception with the caught exception
                    throw new RuntimeException(e);
                }
                return null;
            });
  
            // Wait for the task to complete with a timeout of 5 seconds
            future.get(5, TimeUnit.SECONDS); 
        } catch (TimeoutException e) {
             
            System.err.println("Operation timed out");
        } catch (Exception e) {
            
            e.printStackTrace();
        } finally {
            // Shut down the executor
            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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads