Swingworker Timeout

2019-02-24 08:57发布

问题:

I am using a SwingWorker to read data over a TCP connection and display when it comes back.

new SwingWorker<EnvInfoProto, Void>() {
  @Override
  public EnvInfoProto doInBackground() {
    try {   
      xxx.writeTo(socket.getOutputStream());
      return ProtoMsg.parseFrom(socket.getInputStream());
    } catch(IOException ignore) { }
    return null;
  }

  @Override
  public void done() {
    try {
      UpdateGui(get());
    } catch (Exception ignore) {}
  }
}.execute();

The problem arises when the socket is dead, e.g. after writeTo it waits eternally for input on the socket. What is the easiest way to timeout after a while? Is this also the best solution in this case? Would I still use a swingworker in that solution?

Thanks

回答1:

Yes, the solution you linked to is a reasonable and easy solution ("best" is so subjective :) You could leverage SwingWorker#get, that is part of the Future interface:

SwingWorker<EnvInfoProto, Void> worker = new SwingWorker<EnvInfoProto, Void>() {
    ...
};
worker.execute();
worker.get(15, TimeUnit.SECONDS); 
//will block 15 seconds at most, then throw TimeoutException

Of course you could come up with different ways to reach your goal, but I'd bet there is more code involved than in this solution, so I'd give it a try.