私のメソッドは、メソッドが終了していない場合、3 秒以内にcheckConnection()
呼び出しメソッドを終了する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();
}
}
}