I figure out the future while I wait for a sequential event:
Future<Response> 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); }
The CommunicationTask class implemented the Observer interface to listen for changes from the serial port.
The problem is that reading from the serial port is relatively slow, and even when a serial event occurs, the time runs out and a TimeoutException . What can I do to stop the timeout of my future when a sequential event occurs?
I tried it with AtomicReference but didn't change anything:
public class CommunicationTask implements Callable<Response>, 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(); } }
What can I do to solve this problem?
EDIT:
Ok, I had one mistake. I counted my latch for setting atomicResponse in my update function. Now this seems to work, but is there still a question, is this approach suitable for this?
source share