Issue
This is just an example. I have an input stream and I want to set an listener for it. How can 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 decrease 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. What is the explanation?
Solution
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.
Answered By - nquincampoix
Answer Checked By - Marilyn (JavaFixing Volunteer)