babellog

Friday, July 30, 2004

Loop Spike



I was once scanning an InputStream where the end of stream is not known. Only way out was kind of knowing what is the Character or string pattern that will be at the end of the stream and stop reading from the stream as soon as you encounter that pattern (You will encounter situation when you use TelnetClient from Jakarta Commons Net). Otherwise since InputStream in Java was blocking (prior to non-blocking IO was introduced) your code will get stuck at read() method and will not get out. I was not always sure what the string pattern the stream would end with. Anyway cut the story short, I ended up scanning the stream in a loop and introduced timeout to get out of the loop if I don't find what I am looking for.

This introduced a new problem, the processor utilization spiked to 100% (Obviously :-)) But introducing a Thread.sleep(1) brought back the processor back to normal. Since I can't replicate the whole code in this blog, here is a loop that checks for an existence of a file and reports you (if you add a System.out.println around f.exists()) as soon as it is created. Run the code with the comments on and comments off and check the processor utilization.

Who knows, it might become handy when you are trying to scan a stream from a telecom switch far away in a pacific island :-)

import java.io.File;


 
public class LoopSpike {
public LoopSpike() {
}

public static void main(String[] args) {
File f = new File("test.txt");
while (true){

f.exists();
// try {
// Thread.sleep(1);
// }
// catch (InterruptedException ex) {
// }
}
}

}

0 Comments:

Post a Comment

<< Home