我正在计算等待串行事件发生超时的未来:
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);
}
该类CommunicationTask
已实现Observer
接口以侦听来自串行端口的更改。
问题是从串行端口读取相对较慢,即使发生串行事件,时间也会耗尽并TimeoutException
抛出 a。当串行事件发生时,我能做些什么来停止我未来的超时时钟?
我试过了,AtomicReference
但这并没有改变任何东西:
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();
}
}
我能做些什么来解决这个问题?
编辑:
好的,我有一个错误。atomicResponse
在设置函数之前,我正在倒数我的闩锁update
。现在它似乎奏效了,但仍然存在这样的问题,如果这种方法是正确的方法吗?