How to prevent application freezing if the server is unavailable?

InetAddress serverAddr = InetAddress.getByName(serverAddress);
String hostname = serverAddr.getCanonicalHostName();
Socket socket = new Socket(serverAddr, portNumber);
// Freezes before this line if the server is unavailable
socket.setSoTimeout(3000);

Does anyone know how to implement server availability checking or prevent freezing?

+3
source share
3 answers

Using a constructor with two arguments , you will immediately say Java. What you are looking for is probably

Socket socket = new Socket();
// Configure socket here
socket.connect(new InetSocketAddress(serverAddr, portNumber), 3000);
if (! socket.isConnected()) {
    // Error handling
} else {
    // Use socket
}

It will still be locked for 3 seconds. If you want to prevent this, use a stream to connect.

+6
source

I am going to advise the obvious: use a separate thread to do this. The thread can freeze without freezing the application.

+3
source

( , " " ), , .)

In addition, if this happens often, you want to use Executor(thread pool) instead of manually creating your own Thread- creating / deleting threads is expensive.

I also ignore exception handling in this snippet (which is not completely trivial.)

Runnable runnable = new Runnable() {
   public void run() {
      InetAddress serverAddr = InetAddress.getByName(serverAddress);
      String hostname = serverAddr.getCanonicalHostName();
      Socket socket = new Socket(new InetSocketAddress(serverAddr, portNumber), 3000);
      /* ... do more of your after-connection processing here, assuming it doesn't
       * need to be in the original "dispatch" thread.
       */
   }
};

Thread t = new Thread(runnable);
t.start();
0
source

Source: https://habr.com/ru/post/1705035/


All Articles