title: NullPointerException thrown from Socket.getInputStream()
body: <p>I am getting a NullPointerException raised in this code very rarely. This is part of a video streaming application that consumes multiple RTSP streams simultaneously, and disconnects and reconnects to them regularly (i.e. based on the user).</p>
  
  <pre><code>private void openSocket() throws IOException {
    rtspSocket = new Socket();
    rtspSocket.connect(new InetSocketAddress(ip, port), connectionTimeout);
    rtspSocket.setSoTimeout(readTimeout);
  
    // NullPointerException on next line
    bufStream = new BufferedInputStream(rtspSocket.getInputStream());
  }
  </code></pre>
  
  <p>The stack trace is as follows:</p>
  
  <pre><code>java.lang.NullPointerException
  at java.io.FileInputStream.&lt;init&gt;(Unknown Source)
  at java.net.SocketInputStream.&lt;init&gt;(Unknown Source)
  at java.net.PlainSocketImpl.getInputStream(Unknown Source)
  at java.net.Socket$2.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.Socket.getInputStream(Unknown Source)
  at my.code.shown.above()
  </code></pre>
  
  <p>My Google-fu has pulled up <a href="http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=921c4f414d0015ffffffffae4925115a07609?bug_id=4332294" rel="nofollow">this bug from Apr 2000</a> and <a href="http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=e8898331143238ee81d14a20da4?bug_id=4091706" rel="nofollow">this bug from Nov 1997</a> but I am not convinced they are applicable. I have also had a wander through the JDK 1.6 update 7 code that I am building against and noticed that this exception is only raised whenever the <code>FileDescriptor</code> that is contained in the <code>PlainSocketImpl</code> is null. This value is then passed into the <code>FileInputStream</code> constructor from the <code>SocketInputStream</code> constructor.</p>
  
  <p>Short of catching the NPE and throwing an IOException, is there something I can do here? My suspicion is that this is caused by some sort of IOException that sets the FileDescriptor to null. It would be much easier if an IOException was thrown instead!</p>