Skipping the BufferedReader readLine() method in java
Is there a easy way to skip the readLine() method in java if it takes longer than, say, 2 seconds?
Here's the context in which I'm asking this question:
public void run()
{
boolean looping = true;
while(looping) {
for(int x = 0; x<clientList.size(); x++) {
try {
Comm s = clientList.get(x);
String str = s.recieve();
// code that does something based on the string in the line above
}
开发者_开发知识库 // other stuff like catch methods
}
}
}
Comm is a class I wrote, and the receive method, which contains a BufferedReader called "in", is this:
public String recieve()
{
try { if(active) return in.readLine(); }
catch(Exception e) { System.out.println("Comm Error 2: "+e); }
return "";
}
I've noticed that the program stops and waits for the input stream to have something to read before continuing. Which is bad, because I need the program to keep looping (as it loops, it goes to all the other clients and asks for input). Is there a way to skip the readLine() process if there's nothing to read?
I'm also pretty sure that I'm not explaining this well, so please ask me questions if I'm being confusing.
The timeout alone is not a good idea. Use one thread per client (or use asynchronous I/O, but unless you're building some high performance application, that's unnecessarily complicated).
As for the timeout itself, it must be done on the stream that's encapsulated. See for example How can I set a timeout against a BufferedReader based upon a URLConnection in Java?
精彩评论