What keeps this thread alive?

I have this sun example of how to read data from a serial port http://developer.java.sun.com/developer/releases/javacomm/SimpleRead.java.
I'm not interested in the serial port stuff but I wonder what exactly keeps the program / the thread alive?
The entire code:
* @(#)SimpleRead.java     1.12 98/06/25 SMI
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
* Sun grants you ("Licensee") a non-exclusive, royalty free, license
* to use, modify and redistribute this software in source and binary
* code form, provided that i) this copyright notice and license appear
* on all copies of the software; and ii) Licensee does not utilize the
* software in a manner which is disparaging to Sun.
* This software is provided "AS IS," without a warranty of any kind.
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
* ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE
* SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS
* BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
* HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING
* OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* This software is not designed or intended for use in on-line control
* of aircraft, air traffic, aircraft navigation or aircraft
* communications; or in the design, construction, operation or
* maintenance of any nuclear facility. Licensee represents and
* warrants that it will not use or redistribute the Software for such
* purposes.
import java.io.*;
import java.util.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener
    static CommPortIdentifier portId;
    static Enumeration portList;
    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;
    public static void main(String[] args)
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements())
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
                // print port names to adjust the desired com port
                System.out.println("Serial Port: " + portId.getName());
                // if (portId.getName().equals("COM1")) {
                // this is (hard coded) the port I want to monitor
                if (portId.getName().equals("COM4")) {
                    SimpleRead reader = new SimpleRead();
    public SimpleRead() {
        try {
            serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
        } catch (PortInUseException e) {}
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {}
     try {
            serialPort.addEventListener(this);
     } catch (TooManyListenersException e) {}
        serialPort.notifyOnDataAvailable(true);
        try {
            serialPort.setSerialPortParams(9600,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {}
        readThread = new Thread(this);
        readThread.start();
    public void run() {
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {}
    public void serialEvent(SerialPortEvent event) {
        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:
            byte[] readBuffer = new byte[20];
            try {
                while (inputStream.available() > 0) {
                    int numBytes = inputStream.read(readBuffer);
                System.out.print(new String(readBuffer));
            } catch (IOException e) {}
            break;
}The work of the thread is located in the run() method. As long as statements from this method are executed the thread is alive, at least this is what I've read so far in thread HowTos and stuff.
But:
public void run() {
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {}
    }doesn't contain an endlos loop. It sleeps for a fixed amount of time and then seems to finish. The programm or a thread of the program is still running after these 20 seconds expired and keeps reading data.
I've also seen a version with 100 ms instead of 20000.
So now back to my question: Why is this working?
Why 20000?
Can somebody enlighten me please?
I was going to implement an endlos loop to keep such a port monitoring thread alive but since the jave gurus shipped the example this way I'm kinda puzzled.
Any help is highly appreciated.
Mat.

As far as I know the serialEvent() method is a callback. (I think the registered listeners are usually callback aren't they).
I wish I could rely on this kind of technique. I even read some Thread faqs and howtos over but I couldn't figure out why this should be reliable working.
Maybe its just because the opening of the port leads to another thread created. The one which monitors the port in the first place and calls the registered listeners. So the 20 seconds may just be a very safe way to let this thread do all its initial work.
But then ... why doing a seperate thread in SimpleRead?
Thank you so far for your input,
Mat.

Similar Messages

Maybe you are looking for

  • Error while installing Database 10g on Linux Enterprise 5

    Hi All, When I tried to install Database 10g this error apears All installer requirements met. Preparing to launch Oracle Universal Installer from /tmp/OraInstall2009-02-05_12-55-24PM. Please wait ...bash-3.2$ Exception in thread "main" java.lang.Uns

  • Setting flag account assignment element in PS within BADI doesn't work

    Hello, I would like to set the flag for account assignement element and billing element in PS depending on some fields of cProjects. Hint 993642 says that can be done in GCC_PS_PROJECT_LABEL. Unfortunately I don't know how to pass some parameters fro

  • IOS 5 And IOS 5.0.1

    What are the differences between ios 5 and ios 5.0.1 ?  Thanks

  • Which is better to use Shell Script or Alerts in OMS

    HI This is a point of confusion for me to decide that for monitoring the databases what should be used the Alerts Set in the Management Server or Shell scripts . May I have your valuable suggestions with reason for supporting the suggestion

  • Firefox "stops working" and shuts down every few mins or less.

    A message pops up that says Firefox has stopped working and to close the program. I can "refresh" to the same spot but it's happening every few mins or less. Any suggestions? It's only been happening for the past 3 days, and like others who's systems