Home > Software engineering >  setting listener for an input stream in java
setting listener for an input stream in java

Time:02-04

This is just an example. I have an input stream and i want to set an listener for it. how i can do it. the first way is creating a background thread that checks it repeatedly.

Thread thread = new Thread() {
    public void run() {
        while(true) {
            Thread.sleep(100);
            //optional sleep to avoid wasting cpu cycles
            int c;
            if((c = in.read()) != -1)
                addEventToUIthread(c);
        } 
    } 
} 

but i think without Thread.sleep it will waste cpu cycles. and with it; it will decreases accuracy to get events. assume that the input stream is an file that an inaccessible output stream is writing to it. this is just an example to illustrate that i don't know the amount of runtime cost of such background threads. please explain about it.

CodePudding user response:

If you want to read input bytes immediately, you don't need to use Thread.sleep here to protect CPU cycles, because InputStream.read() method runs synchronously, in other words, it blocks until one byte is available.

However if you want to intentionally slow down CPU usage while reading data, using Thread.Sleep would be the correct way.

CodePudding user response:

If you want your program to keep reading a file after it has reached the end, without any pause between attempts, then from the moment the read() function returns -1 for the first time, to the moment new data arrives, your program will use all CPU time available, since it will only go back and forth to the read() function, which is not a background operation.

The same goes with any other loop containing only foreground operations.

  •  Tags:  
  • Related