title: Is it possible to read from a InputStream with a timeout?
body: <p>Specifically, the problem is to write a method like this:</p>
  
  <pre><code>int maybeRead(InputStream in, long timeout)
  </code></pre>
  
  <p>where the return value is the same as in.read() if data is available within 'timeout' milliseconds, and -2 otherwise.  Before the method returns, any spawned threads must exit.</p>
  
  <p>To avoid arguments, the subject here java.io.InputStream, as documented by Sun (any Java version).  Please note this is not as simple as it looks.  Below are some facts which are supported directly by Sun's documentation.</p>
  
  <ol>
  <li><p>The in.read() method may be non-interruptible.</p></li>
  <li><p>Wrapping the InputStream in a Reader or InterruptibleChannel doesn't help, because all those classes can do is call methods of the InputStream.  If it were possible to use those classes, it would be possible to write a solution that just executes the same logic directly on the InputStream.</p></li>
  <li><p>It is always acceptable for in.available() to return 0.</p></li>
  <li><p>The in.close() method may block or do nothing.</p></li>
  <li><p>There is no general way to kill another thread.</p></li>
  </ol>