views:

254

answers:

1

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.

+3  A: 

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 http://stackoverflow.com/questions/93357/

Artefacto
Using `BufferedReader` or `BufferedInputStream` on an underlying Reader/Stream that has a timeout is also dangerous. These Buffered classes do not attempt to recover from a time out so you can lose partially transmitted packets.
Kevin Brock
The example doesn't seem to be very relevant, since those setReadTimeout methods only work with those URLConnection classes. Anyway, I took your first suggestion. Thanks Artefacto.
DDP