title: java.net.UnknownHostException and java.net.SocketException: Too many open files
body: <p>I am running a web application on Tomcat. My application make connection to other web services to fulfill request from client. Sometime i get java.net.UnknownHostException while opening URL connection and then after sometimes I start getting java.net.SocketException: Too many open files. And my server stops accepting connection further. Please guide. </p>
  
  <pre><code>String  response;
      HttpURLConnection conn = null;
  BufferedReader rd = null;
  InputStream in = null;
  try
  {
      // Send data
      String urlStr = URL;
      URL url = new URL(urlStr);
      conn = (HttpURLConnection)url.openConnection();
      conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
      int contentLength = conn.getContentLength();
      //   System.out.println("content length 1" +  contentLength);
      if (contentLength &lt;= 0)
      {
          InputStream in1 = (conn).getErrorStream();
          if (in1 != null)
          {
              in1.close();
          }
          conn.getInputStream().close();
          in = null;
          conn.disconnect();
          conn = null;
          return null;
      }
      in = conn.getInputStream();
      if (conn.getResponseCode() != 200)
      {
          InputStream in1 = (conn).getErrorStream();
          if (in1 != null)
          {
              in1.close();
          }
          conn.getInputStream().close();
          in = null;
          conn.disconnect();
          conn = null;
          in.close();
          in = null;
          return null;
      }
      // Get the response
      rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      StringBuffer stringBuffer = new StringBuffer();
      String line = null;
      while ((line = rd.readLine()) != null)
      {
          stringBuffer.append(line);
      }
      response = stringBuffer.toString();
      System.out.println("full ads response = " + response);
  }
  catch (Exception ex)
  {
      //   ex.printStackTrace();
  }
  finally
  {
      try
      {
          if (conn != null)
          {
              InputStream in1 = (conn).getErrorStream();
              if (in1 != null)
              {
                  in1.close();
              }
              conn.getInputStream().close();
              in = null;
              conn.disconnect();
              conn = null;
          }
          if (rd != null)
          {
              rd.close();
              rd = null;
          }
          if (in != null)
          {
              in.close();
              in = null;
          }
      }
      catch (Exception e)
      {
      }
  }
  return null;        
  </code></pre>