내 메소드 checkConnection()
setPort()
을 으로 호출합니다.이 메소드는 메소드가 완료되지 않은 경우 3 초 이내에 호출 메소드를 종료합니다. 위대한 작품과 시간 제한을 초과했을 때 com.google.common.util.concurrent.UncheckedTimeoutException
의 예외가 있습니다. 그러나이 예외가 throw 된 후에도 setPort
이 여전히 실행되고 한 번 완료되면 내 try 문 내에서 포트가 열리면 코드가 실행되고 Thread.sleep(100)
이되면 InterruptedException이 발생하고 메서드가 종료됩니다. 그러나 이로 인해 문제가되는 포트가 생겨납니다. 제한 시간이 초과되어 call()
메서드 내의 모든 코드가 중지되는 방식이 있습니까?Java 메소드 완전히 종료
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();
}
}
}
setPort()의 구현 중 적어도 일부를 제공하면 도움이 될 것이라고 생각합니다. – Scadge
내 코드에 추가했습니다. –