javax.comm.portinuseexception port currently owned by

1.5k Views Asked by At

I've made a program that connects to a device via rs232. It all works perfectly fine until I close the connection and try to reopen it again from the same application. I get the following exception:

javax.comm.PortInUseException: Port currently owned by controller.Application
        at javax.comm.CommPortIdentifier.open(CommPortIdentifier.java:310)
        at controller.Application.connect(Application.java:30)
        at controller.Application.send(Application.java:63)

When I close my application entirely and restart it I am able to connect to the port again. But i need to use that port again without closing my entire application. I tried to close my port as shown below but it is not working as i want:

public void disconnect() {
        if (serialPort != null) {
            try {
                in.close();
                out.close();
                serialPort.removeEventListener();
                serialPort.close();
                commPort.close();
            } catch (Exception ex) {
                System.out.println("When closing: " + ex);
            }
        }

    }

How should or could I close my port to avoid this exception?

1

There are 1 best solutions below

0
On

You can use

                    if (serialPort != null)
                    {
                        serialPort.close();
                    }

I hope it'll help