I am using the j2mod Modbus library 3.1.1 with Java 8. In my JavaFX application, I created a wrapper class to handle the interaction with the Modbus slave instance. The wrapper class implements the Runnable interface so as not to freeze the UI when opening and closing the slave. But I am getting an exception when I try to close the slave. How can I fix that? Below is the snippet of the wrapper class and the logs after I call closeSlave method.
@Slf4j
public class ModbusSlaveWrapper implements Runnable {
// Private fields
private volatile boolean running = true;
void createSlave() {
try {
slave = ModbusSlaveFactory.createUDPSlave(InetAddress.getByName(ipAddress), port);
int unitId = 1;
slave.addProcessImage(unitId, processImage);
log.info("Slave created and process image is added");
slave.open();
log.info("Slave is listening");
} catch (Exception e) {
log.error(e.getMessage());
}
}
public void closeSlave() {
log.info("Closing the slave");
running = false;
}
@Override
public void run() {
while (running) {
if (slave == null) {
createSlave();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error(e.getMessage());
}
}
try {
ModbusSlaveFactory.close();
} catch (Exception e) {
log.error(e.getMessage());
} finally {
log.info("Closed the slave");
}
// Other methods
}
1:07:46.015 [Thread-9] INFO g.t.r.c.w.t.m.ModbusSlaveWrapper - Slave created and process image is added 11:07:46.068 [Thread-9] INFO g.t.r.c.w.t.m.ModbusSlaveWrapper - Slave is listening 11:07:51.682 [JavaFX Application Thread] INFO g.t.r.c.w.t.m.ModbusSlaveWrapper - Closing the slave 11:07:57.219 [Thread-9] INFO g.t.r.c.w.t.m.ModbusSlaveWrapper - Closed the slave 11:07:57.232 [Modbus UDP Listener [port:502]] ERROR c.g.j.modbus.ModbusUDPListener - Exception occurred before EOF while handling request com.ghgande.j2mod.modbus.ModbusIOException: I/O exception - failed to read at com.ghgande.j2mod.modbus.io.ModbusUDPTransport.readRequest(ModbusUDPTransport.java:104) ~[j2mod-3.1.1.jar:3.1.1] at com.ghgande.j2mod.modbus.AbstractModbusListener.handleRequest(AbstractModbusListener.java:155) ~[j2mod-3.1.1.jar:3.1.1] at com.ghgande.j2mod.modbus.ModbusUDPListener.run(ModbusUDPListener.java:107) ~[j2mod-3.1.1.jar:3.1.1] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121] Caused by: java.lang.IllegalMonitorStateException: null at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151) ~[na:1.8.0_121] at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261) ~[na:1.8.0_121] at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457) ~[na:1.8.0_121] at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:449) ~[na:1.8.0_121] at com.ghgande.j2mod.modbus.UDPSlaveTerminal.receiveMessage(UDPSlaveTerminal.java:122) ~[j2mod-3.1.1.jar:3.1.1] at com.ghgande.j2mod.modbus.io.ModbusUDPTransport.readRequest(ModbusUDPTransport.java:94) ~[j2mod-3.1.1.jar:3.1.1] ... 3 common frames omitted