2

I have snippet of RXTX serial communication sample:

public static class SerialReader implements Runnable {
    InputStream in;

    public SerialReader(InputStream in) {
        this.in = in;
    }

    public void run(){
        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            while ((len = this.in.read(buffer)) > -1){
                System.out.print(new String(buffer,0,len));   
            }    
        }
        catch(IOException e) {
            e.printStackTrace();
        }            
    }
}

I'm wondering regarding while cycle. According to my understanding such non ending while cycles should be overkill for system and should be avoided. But when I looked ad task manager I couldn't find significant load.

Then I changed while cycle as below and got system overload.

        while (true) {
            System.out.print(new String(buffer,0,0));
        }

Why firs approach not generates high load? How I can make second cycle to make not so hungry for CPU? Is it good practice to use such algorithms at all?

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
vico
  • 17,051
  • 45
  • 159
  • 315
  • "Is it good practice to use such algorithms at all?" That depends. What are you trying to do in your loop? Check for IO? If so, polling, as it's called, for IO has is disadvantages. Take a look at this so question https://stackoverflow.com/questions/3072815/polling-or-interrupt-based-method – MeetTitan Nov 06 '18 at 13:44

1 Answers1

0

Operation in.read(buffer) takes some time, because your program waits for I/O to return the next character.

It is a so-called blocking operation. From Javadoc: This method blocks until input data is available, the end of the stream is detected, or an exception is thrown. So, in this case, every iteration of loop happens not so often, therefore it doesn't generate high load.

As Mike Robinson pointed out, this kind off loop can be also called busy wait.

In your second example while(true) is not waiting for anything. Therefore there is no delay between consecutive iterations and it generates very high load.

Of course, if RXTX transmitter would be very fast, it might deplete resources of CPU/memory. In this case, it might be a good idea to add some memory/CPU limit for your applications. You could also read characters in chunks (there is overloaded read method in InputStream which can read some number of characters) and add maybe some delay between reads.

In case you know that coming stream won't be so fast, that it would deplete resources of your application, the approach used in your example is correct.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76