如果方法未完成,我的方法checkConnection()
调用在 3 秒setPort()
内退出调用方法。TimeLimiter
这很好用,com.google.common.util.concurrent.UncheckedTimeoutException
超过时间限制时有一个例外。但是,即使在引发此异常之后setPort
仍然会运行并且一旦完成,我的 try 语句中打开端口的代码也会运行,但是一旦遇到Thread.sleep(100)
InterruptedException 就会引发该方法退出。然而,这给我留下了一个导致问题的开放端口。有没有办法一旦超过时间限制,call()
方法中的所有代码都会停止?
public static String checkConnection(final String comPort) {
final String port = comPort;
String result = null;
TimeLimiter limiter = new SimpleTimeLimiter();
try {
result = limiter.callWithTimeout(new Callable<String>() {
public String call() {
// Try to set serial port
String setPort = setPort(comPort);
// Check for any exceptions
if(setPort.contains("jssc.SerialPortException")) {
if(setPort.contains("Port busy")) {
return "Error: The port appears to be busy";
} else {
return "Error: Can't connect to port";
}
}
try {
// Port can't be accessed twice at the same time
synchronized(portLock) {
// Open port if not already opened
if(!serialPort.isOpened())
serialPort.openPort();
// Sleep while response is being sent
Thread.sleep(300);
// Check for response
buffer = serialPort.readBytes(6);//Read 6 bytes from serial port
serialPort.closePort();
}
// Parse response as string
response = new String(buffer);
} catch (SerialPortException | InterruptedException e) {
System.out.println("Serial:: ping() :: Exception while pinging Noteu : " + e);
return "Error";
}
return response;
}
}, 3, TimeUnit.SECONDS, false);
} catch (Exception e) {
System.out.println("Serial:: checkConnection() :: Exception while calling ping : " + e);
}
}
public static String setPort(String port) {
synchronized(portLock) {
try {
System.out.println("Serial:: setPort() :: Opening Port...");
serialPort = new SerialPort(port);
if(!serialPort.isOpened())
serialPort.openPort();
System.out.println("Serial:: setPort() :: Setting Params...");
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
System.out.println("Setting Port3");
serialPort.closePort();
System.out.println("Serial:: setPort() :: Port Set...");
return "Success";
} catch (SerialPortException e) {
System.out.println("Serial:: setPort() :: Exception at set Port : " + e.toString());
return e.toString();
}
}
}