1

I have a SwingWorker which is supposed to execute 3 methods sequentially one after another. The method 1 contains a while loop for a BufferedReader. This while loop never terminates as the BufferedReader is never signalled with an end. I want to terminate the loop using some kind of a timer after 5 seconds. How do I do this?

    public class TestWorker extends SwingWorker<Void,Void>{
        public TestWorker(){
        }

        private void doSomething1(){
            TelnetClient telnetClient
            telnetClient = new TelnetClient();
            telnetClient.connect(telnet_IPAddress, telnet_Port);

            InputStream telnetInputStream = telnetClient.getInputStream();

            try (BufferedReader br = new BufferedReader(new InputStreamReader(telnetInputStream))) {
                String line;
                while ((line = br.readLine()) != null) {
                    //Do something
                    //The bufferedreader is not signaled with an end of a stream. I want to terminate this loop after 5 seconds.
                }
            } catch (IOException ex) {
            }
        }

        private void doSomething2(){
        }

        private void doSomething3(){
        }

        @Override
        public Void doInBackground() {
            doSomething1();
            doSomething2();
            doSomething3();
            return null;
        }

        @Override
        public void done() {
            //Update something on a GUI
        }
    }
jadrijan
  • 1,438
  • 4
  • 31
  • 48
  • Is there a consistent stream of input or, once it's done, does it just sit waiting on a single call of `readLine`? Meaning if you put a `println` in the while-loop, will things get printed the whole time, or will it stop printing eventually? – Bernhard Barker Jun 18 '13 at 14:41
  • 1) Change code of the form `catch (Exception e) { ..` to `catch (Exception e) { e.printStackTrace(); // very informative! ..` 2) For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Jun 18 '13 at 14:45
  • is instance of SwingWorker somehow Swing related, if not then to use plain Executor, otherwise post an [SSCCE](http://sscce.org/), short, runnable, compilable, [can be based on](http://stackoverflow.com/questions/7053865/cant-get-arrayindexoutofboundsexception-from-future-and-swingworker-if-threa) – mKorbel Jun 18 '13 at 14:47
  • @Dukeling I get the InputStream from a telnet session (I use the apache commons net). As far as I can see it just waits, never terminates, but it will not print the whole time. – jadrijan Jun 18 '13 at 15:10
  • 1
    An option is to [put a timeout on the InputStream](http://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-inputstream-with-a-timeout) (assuming it's fine to "stop after X seconds after not having read anything", as opposed to "read for Y seconds, then stop"). – Bernhard Barker Jun 18 '13 at 15:58

0 Answers0