I have a java application that reads data from a serial port /dev/ttyUSB0
. This application runs on Linux, using RXTX library to access the serial port from java.
Sometimes the serial port isn't closed properly by a worker thread, and when starting a new one I get javax.comm.PortInUseException
.
Worker threads get stuck while calling close()
method. This has already been asked but I cannot directly apply that hack.
Is there a way to force Linux to close the port? I can call external processes and run shell scripts as root. Once the port is closed by the OS, I intend to handle the proper exception in java.
I can't reboot the machine.

- 1
- 1

- 4,571
- 20
- 40
- 64
2 Answers
First, you should debug your code and make sure that the thread responsible for closing the device node really does close it; since you're talking about access to a non-shareable hardware device, using the Holder pattern for the RXTX connection might be helpful.
If the program isn't properly closing the device node, the only option is to kill it. You can use fuser /dev/ttyUSB0
to see what process has it open and then kill
that PID. This doesn't require root privileges, just access as the user who owns the process to be killed.

- 75,269
- 21
- 115
- 152
-
The process that is using it is his java process. Although killing it would solve it I don't think that's a proper solution. – Sep 09 '13 at 16:51
-
Of course it's the Java process, but the only way to get the port unwedged if the process won't close it is to kill the offending process. – chrylis -cautiouslyoptimistic- Sep 09 '13 at 16:51
I actually faced this problem at work a few months back (at least it looks a lot like it). I spent a lot of time (like a week) on it. I looked through the native code and found the issue (it's in the RXTX lib).
I'm going to recommend you implement the same solution I did - manage your threads and your ports properly! You shouldn't be relying on PortInUseException to check if a port is opened anyway - that's for 'exceptional' cases.
Just make sure you:
- Always call close on an opened port
- Never call open on an opened port
If you'd rather work around it than do it the right way - the issue is in the native app, so you need to find a way to 'restart' it. In my case it was all inside an OSGi framework so I could just uninstall the bundle that contained the native app and then install it again. In your case it might require restarting the whole Java process
-
-
In my case that happened because of calling open twice on the same port without closing it after the first open. If you don't call open on already opened ports close() won't block forever. – Sep 10 '13 at 07:28
-
after fixing the code as you suggested, the port doesn't get locked anymore. Thank you. – Alessandro Da Rugna Oct 02 '13 at 08:43