Ping a server without freezing the Thread

325 Views Asked by At

I tried to use multiple threads, sadly no luck:

public synchronized boolean pingServer(final String ip, final short port) {
    final boolean[] returnbol = new boolean[1];
    Thread tt = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket s = new Socket(ip, port);
                s.close();
                returnbol[0] = true;
            } catch (IOException e) {
                returnbol[0] = false;
            }
        }
    });
    tt.start();
    try {
        tt.join();
    } catch (InterruptedException e) {
        tt.stop();
    }
    tt.stop();
    return returnbol[0];
}

The main thread still Freezes for some reason.

Is there a "lagless" way to ping a server?

2

There are 2 best solutions below

0
On BEST ANSWER

What exactly did you want to got in

try {
        tt.join();
    } catch (InterruptedException e) {
        tt.stop();
    }

block? Here you joined to parallel thread and waits till this thread will ends (got ping result).

You have next options:

  • Wait till ping ends
  • Don't wait... and don't got result
  • Use some concurrency classes like Future<> to got result (but you will block thread at moment you ask result if it not retrieved yet)
  • Or you can use some 'callback' function/interface to threw result from inner 'ping' thread.
0
On

You will need to remove the following lines from your code. The tt.join() will force the main thread to wait for tt to finish.

try {
    tt.join();
} catch (InterruptedException e) {
    tt.stop();
}
tt.stop();

Use a Future instead to get the result for later use