title: How to stop timeout of a future
body: <p>I'm computing a future for having a timeout in waiting for a serial event to happen:</p>
  
  <pre><code>Future&lt;Response&gt; future = executor.submit(new CommunicationTask(this, request));
  response = new Response("timeout");
  try {
    response = future.get(timeoutMilliseconds, TimeUnit.MILLISECONDS);
  } catch (InterruptedException | TimeoutException e) {
    future.cancel(true);
    log.info("Execution time out." + e);
  } catch (ExecutionException e) {
    future.cancel(true);
    log.error("Encountered problem communicating with device: " + e);
  }
  </code></pre>
  
  <p>The <code>CommunicationTask</code> class has implemented the <code>Observer</code> interface to listen to an change from the serial port.</p>
  
  <p>The problem is that reading from the serial port is relatively slow and even when a serial event is happening the time runs out and a <code>TimeoutException</code> is thrown. What can I do to stop the timeout clock of my future when a serial event is happening?</p>
  
  <p>I tried it with an <code>AtomicReference</code> but that didn't change anything:</p>
  
  <pre><code>public class CommunicationTask implements Callable&lt;Response&gt;, Observer {
    private AtomicReference atomicResponse = new AtomicReference(new Response("timeout"));
    private CountDownLatch latch = new CountDownLatch(1);
    private SerialPort port;
  
    CommunicationTask(SerialCommunicator communicator, Request request) {
      this.communicator = communicator;
      this.message = request.serialize();
      this.port = communicator.getPort();
    }
  
    @Override
    public Response call() throws Exception {
      return query(message);
    }
  
    public Response query(String message) {
      communicator.getListener().addObserver(this);
      message = message + "\r\n";
      try {
        port.writeString(message);
      } catch (Exception e) {
        log.warn("Could not write to port: " + e);
        communicator.disconnect();
      }
      try {
        latch.await();
      } catch (InterruptedException e) {
        log.info("Execution time out.");
      }
      communicator.getListener().deleteObserver(this);
      return (Response)atomicResponse.get();
    }
  
    @Override
    public void update(Observable o, Object arg) {
      atomicResponse.set((Response)arg);
      latch.countDown();
    }
  }
  </code></pre>
  
  <p>What can I do to solve this problem?</p>
  
  <p>EDIT:</p>
  
  <p>Ok I had one error. I was counting down my latch befor setting the <code>atomicResponse</code> in my <code>update</code> function. Now it seems to work, but there's still the question if this approach is the right way to do so?</p>