?
Solved

Non-blocking read problem

Posted on 2001-07-23
9
Medium Priority
?
406 Views
Last Modified: 2007-12-19
I wonder if you could take a look at the following code. As some of you will know, in some cases, the only way to break out of a blocking read is to cause an exception to be thrown by attempting to close the stream. This code attempts to use that principle but doesn't work. Working code correction gets you the points!

/*
Having had some problems reading from stdout
and stderr got from the Process class, I decided
to implement a stream reader with a 'blocking
time out', that is to say a stream reader that
will allow blocking for blockingTimeout milliseconds.
The code below represents a crude test bed for proof
of concept.

The problem seems to be that once the thread reading
System.in has started blocking, an attempt to close
close System.in (yes I know that is a dubious concept, but
it will have the desired effect, i.e. to throw an exception
and stop the read) only succeeds if it is called immediately,
thus rendering my blockingTimeout completely useless!
*/
import java.util.*;
import java.io.*;

public class StreamReader {
  InputStream in;
  String type;
  OutputStream out;
  long blockingTimeout = 500;
  private Thread internalThread;

  public StreamReader(InputStream in,String type){
    this.in = in;
    this.type = type;
  }

  public static void main(String[] args){
    StreamReader sr = new StreamReader(System.in,"");
    sr.read();
  }

  public void read(){
    Runnable r = new Runnable() {
    int c = -1;
      public void run(){
        try {
          // deliberately cause a blocking read of System.in
          while((c = in.read()) > -1){
          }
        }catch(Exception e){
          System.err.println("stopped (reported from runnable)");
        }
      }
    };
    internalThread = new Thread(r);
    internalThread.start();

    try {
      // If the following is uncommented, in.close() is never called on Win 2000 [unless you press a key!]
      //Thread.sleep(blockingTimeout);
      in.close();
    }catch(Exception e){
      e.printStackTrace();
    }
  }
}
0
Comment
Question by:CEHJ
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +2
9 Comments
 
LVL 3

Expert Comment

by:rjackman
ID: 6308452
hi
this code is working fine on my machine
it comes out of thread on exception rather than blocking
Cheers
RJ
0
 
LVL 86

Author Comment

by:CEHJ
ID: 6308482
Well the Thread.sleep() call at the end should be uncommented. Did you uncomment it, and if so did it work *then*?
0
 
LVL 5

Expert Comment

by:nebeker
ID: 6309525
With the "sleep()" call commented out, the program works fine on Solaris and NT 4.0.

With the "sleep()" call un-commented, the program works fine on Solaris, but hangs on NT 4.0 until the enter key is pressed.

My guess is that it has something to do with the way Windows handles input buffering for console apps.
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 92

Expert Comment

by:objects
ID: 6310476
Plus I'm not sure if closing stdin is a valid thing to be doing.
Changing the code to use a FileInputStream instead, works fine with the sleep uncommented.

0
 
LVL 5

Expert Comment

by:nebeker
ID: 6310937
There's no problem with closing stdin - it's just another input stream like everything else.
0
 
LVL 3

Expert Comment

by:Sendoh
ID: 6311014
hi !!
i'd try this on winnt4.0
dono is this what u want...:)

import java.util.*;
import java.io.*;

public class test implements Runnable{
 InputStream in;
 String type;
 OutputStream out;
 long blockingTimeout = 5000;
 private Thread internalThread;

 public test(InputStream in,String type){
   this.in = in;
   this.type = type;
 }

 public static void main(String[] args){
   test sr = new test(System.in,"");
   sr.read();
 }

 public void read(){
   internalThread = new Thread(this);
   internalThread.start();

   try {
     Thread newThread = Thread.currentThread();
     System.out.println("start sleep here");
     // If the following is uncommented, in.close() is never called on Win 2000 [unless you press akey!]
     newThread.sleep(blockingTimeout);
     //internalThread.sleep(blockingTimeout);
     System.out.println("end sleep");
     in.close();
     //throw(new Exception("test"));
   }catch(Exception e){
     e.printStackTrace();
   }
 }

     public void run()
     {
       int c = -1;

       try
       {
         // deliberately cause a blocking read of System.in
         while(true)
         {
             if((c = in.read())>-1)
             {
                 System.out.println("accept:"+c);
             }
         }
       }
       catch(Exception e)
       {
         System.err.println("stopped (reported from runnable)");
       }
     }
}

hope it helps.:)
0
 
LVL 86

Author Comment

by:CEHJ
ID: 6311696
objects: I brought up the matter of closing stdin in my opening comment. As for FileInputStream, I'm looking for an 'all purpose' non-blocking read

sendoh: Your program doesn't exit on Win2k Advanced Server I'm afraid...
0
 
LVL 92

Accepted Solution

by:
objects earned 100 total points
ID: 6311838
It looks to me like the problem you're seeing is not related to blocking reads, but rather an issue with stdin.
Your code (should) work with.

If your simply want to do non blocking IO the have a look at http://www.cs.berkeley.edu/~mdw/proj/java-nbio/
0
 
LVL 86

Author Comment

by:CEHJ
ID: 6311885
Yes thanks, I've seen this library objects. I might take a look into it...
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month10 days, 14 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question