0

I am taking a distributed course. Now, I want to set a timeout for client when it sends or receiving data from a crushed server, and let it reconnect with a available server. I wanna add something here to let client realized the time has already been long enough. sendMessage(new TextMessage(kvjson)); TextMessage resultMsg = receiveMessage();

I thought about using a thread here like a counter, and when the time is out, just skip the up statement. but I realized if there is a crushed server, client may just stuck inside the method and never get a return back. plus I don't know how let main process know that my timeout head has already finished. I think it relates something with interrupt and sleep? After checking online source I am still confused. So I post it here. Thank you for ur answer and patient in advance!

johnway yang
  • 11
  • 1
  • 2
  • If that's an HTTP server, why don't you manage failover/HA using a server-side load balancer? Also, if this is a Java client, you can set a connection and/or a read timeout (you'd need to read the documentation of your specific client) – ernest_k Mar 22 '18 at 18:53
  • I write the client and server on my own. All servers connect with ECS. There is no such client documentation – johnway yang Mar 22 '18 at 18:56
  • If you've set out to reinvent the wheel, at least you can choose to learn from many open source servers and clients. Pick one and check its source code... – ernest_k Mar 22 '18 at 19:00

1 Answers1

0

You can wrap your client call in its own thread and use a Future object to wait for the response. The Future object will wait for as long as you want and can timeout after sometime. You can then deal with the timeout. See example below.

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<String> future = executor.submit(() -> {

        //long running process
        TimeUnit.SECONDS.sleep(10);
        return "finished";
    });

    try {
        future.get(5, TimeUnit.SECONDS);
    } catch (Exception e) {
        //deal with the timeout
    }
Jose Martinez
  • 11,452
  • 7
  • 53
  • 68