Solved

Non-blocking read problem

Posted on 2001-07-23
9
390 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
  • 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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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 25 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
What is the latest versions eclipse neon 2 141
JAVA part two 5 58
micro services spring boot application error 3 149
JUnit 4 @Before and @BeforeClass differences 3 48
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

864 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now