views:

137

answers:

1

I need to listen to a serial input continuously, but NetBeans warns "Invoking Thread.sleep in loop can cause performance problems." I understand why this causes performance problems, but what is the best alternative in Java?

public class SerialIO extends javax.swing.JFrame {
    ...
    class RcvTask extends Thread {
        public void run() {
            try {
                SerInputStream sis = new SerInputStream(serialPort);
                InputStreamReader isr = new InputStreamReader(sis);
                BufferedReader reader = new BufferedReader(isr);
                while (true) {
                    String line = reader.readLine();
                    parse(line);
                    sleep(RX_SLEEP);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    ...
+17  A: 

Why do you need to sleep ?

BufferedReader.readLine() is a blocking operation.


On the same topic :

Colin Hebert
I wish I could double vote for this one.
Peter Lawrey
Apparently, I've not been getting enough sleep.
JackN