开发者

Rxtxcomm error on disconnecting

I am working with a COM port . I successfully opens the COM port and do 开发者_如何学Call the work. While closing the COM port a crash happens. The code is

public void close()
    throws GPSException
  {
    if (serial_port_ != null)
      serial_port_.close();
  }

Error

#
> # An unexpected error has been detected by Java Runtime Environment:
> #
> #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x04049e69, pid=5692,
> tid=4100
> #
> # Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode, sharing
> windows-x86)
> # Problematic frame:
> # C  [rxtxSerial.dll+0x9e69]
> #
> # If you would like to submit a bug report, please visit:
> #   http://java.sun.com/webapps/bugreport/crash.jsp
> # The crash happened outside the Java Virtual Machine in native code.
> # See problematic frame for where to report the bug.


I've managed to find a solution which appears to resolve the problem - it seems as if the Input and OutputStreams are not completely being closed before the serial port is, as these are running in their own threads and are getting caught up in their own data. This is resolved by adding synchronized mutexes which ensure these threads have properly cleaned up before the serial port is closed.

In my SerialConnection class I added boolean fields, stopRead and stopWrite, to indicate when the InputStream and OutputStream threads respectively should stop listening. I also added mutexes stopReadMutex and stopWriteMutex to synchronize these values among the main and read/write threads. Each iteration of their loops, the reader and writer check the stopRead and stopWrite booleans and break their loops.

When my disconnect function is called, I use the mutexes to change the stopRead and stopWrite values before I call the close functions of the respective threads and serialPort, as shown here:

public void disconnect(){
    try {
        synchronized(stopReadMutex)
        {stopRead = true;}
        synchronized(stopWriteMutex)
        {stopWrite = true;}

        portOut.close();
        portIn.close();
        serialPort.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Also, here is a link to the associated source code if anyone would like to take a closer look. http://pastebin.com/C4Fy8mLZ


The error is due to conflicting threads. The best way to avoid this, is to make all methods synchronized:

public synchronized void disconnect() {
  serialPort.close();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜