These two days in debugging Java serial Communication Code, found a problem, in the program run up, send serial signal to the device, Observation Task Manager, Javaw.exe is still running.
If rerun, will be prompted "portinuseexception", that is, the port is occupied, that is, was not closed the program occupied, embodied in the Task Manager is the running of the Javaw.exe.
Normally, the Javaw.exe is automatically turned off after the debug program is finished running. So why can't the javaw.exe shut down automatically?
Think about the reason, other places are easier to understand, sequential execution, the execution of the program will be closed, should not have any problems. A more likely problem is when the program reads the data returned by the device, what resources are not released and so on, because the problem of resource release is often involved in file operations, with other devices, or when communicating with the network.
So take a look at the code that the program receives data, which is also the most important part of getting the data returned by the instrument:
/**
* Implements the method in the interface Serialporteventlistener reads the data received from the string * * public
void Serialevent (Serialportevent event) {
System.out.println ("Serial event:" + Event.geteventtype ());
Switch (Event.geteventtype ()) {case
serialportevent.bi: Case
Serialportevent.oe:
case Serialportevent.fe: Case
serialportevent.pe: Case
serialportevent.cd: Case
serialportevent.cts: Case
SERIALPORTEVENT.DSR: Case
Serialportevent.ri: Case
Serialportevent.output_buffer_empty: Break
;
Case serialportevent.data_available://get to the serial port to return information
//read data, processing ... Break
;
Default: Break
;
}
}
In fact, the omitted code, that is, the processing of data, is only to stay in the data utilization level, does not involve resources to release this kind of content.
Then try to release the resources, look at some of the previous serial definition of the interface, and found that more likely to represent the physical resources are the following three variables:
The input output stream is public
static InputStream InputStream;
public static OutputStream OutputStream;
RS-232 the serial port public
static SerialPort SerialPort;
Input stream, output stream, serial port.
First try to close the input output stream:
Inputstream.close ();
Outputstream.close ();
The observation results showed that the Javaw.exe was still running.
Then try shutting down the serial port:
Serialport.close ();
Run again, and then found the effect, Javaw.exe has been automatically closed.
Description of this serial communication, after the program is completed, you need to display the serial port in the code to shut down, that is, call the SerialPort object's close () method.