Solved

Non-blocking read problem

Posted on 2001-07-23
9
387 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 5

Expert Comment

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

Expert Comment

by:Sendoh
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Yes thanks, I've seen this library objects. I might take a look into it...
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Java virtual machine monitoring tools 3 39
countHi2 challenge 7 43
wordlen challenge 3 46
ArrayIndexOutOfBoundException 9 30
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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…
This video teaches viewers about errors in exception handling.

772 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

14 Experts available now in Live!

Get 1:1 Help Now