My method checkConnection()
calls setPort()
within a TimeLimiter
which exits the call method within 3 seconds if the method isn't finished. This works great and there is an exception of com.google.common.util.concurrent.UncheckedTimeoutException
when the time limit is exceeded. However even after this exception is thrown setPort
still runs and once completed, code within my try statement opening the port runs however once it gets to Thread.sleep(100)
an InterruptedException is thrown then the method exits. However this leaves me with an open port which causes problems. Is there a way once the time limit is exceeded that all code within the call()
method will stop?
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();
}
}
}
Can you try if this works This is the signature of
You are passing amInterruptible as false.Can you try passing true and see if it works .Also I have strong feeling setPort has to be interruptible .For that as User Scadge has commented you need to provide its implementations.Anyways just hoping this quick solution might work for you