Embedded Freaks..

August 8, 2008

How to close serial port in rxtx

Filed under: java — Tags: , , — kunilkuda @ 8:18 am

Well, you’ve opened the port. But how do you clean up your mess once you’ve done with the serial port ?

Here’s some hints to clean up your serial port mess

    public void disconnect() {
        if (serialPort != null) {
            try {
                // close the i/o streams.
            } catch (IOException ex) {
                // don't care
            // Close the port.


  1. How close a port with java Comm ?
    My problem is that multiple thread can access to a specific port and if a thread try to access, for example to COM1 then the current thread that owns the COM1 must release the port.
    You have some ideas how manage this ?


    Comment by carlo — January 25, 2009 @ 5:48 am

  2. I think Java Comm is similar with rxtx, both have the same interface, so the example should work.

    You should create a singleton as serial port arbiter. Therefore, if several threads want to access the serial port, it can ask the arbiter to grant their request. Therefore, no need to open/close serial port every time a different thread wants to access the serial port.

    Comment by kunilkuda — January 28, 2009 @ 11:06 am

  3. Synchronize your primary methods that use the port. That will prevent the close in the middle of the other method using the port.

    Comment by George — January 30, 2010 @ 12:07 pm

  4. how to close several serial ports, with just one button hit?

    Comment by thariq — August 13, 2010 @ 9:53 am

  5. When I try to close the connection as:

    if (serialPort != null){
    catch(Exception e)

    It throws null pointer exception on removeSerialEventListner. I did not add any serialevent to read..
    Please help..

    Comment by saikrishna — October 15, 2010 @ 9:43 pm

  6. If you continuously receiving data from serialport, you will notice that you are not able to close the port, but these code snippet seems to do the job. Good luck

    public void closePort() {
    System.out.println("Closing: " + portId.getName());
            new Thread(){
            public void run(){
                }catch (IOException ex) {}

    Comment by Behamin B — November 18, 2010 @ 7:39 pm

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: