title: ServiceUnavailableException with LDAP and JNDI
body: <p>I am using JNDI to connect to LDAP and I need it to work with many simultaneous TCP connections. All connections need to be established at the same time. The mystery is that sometimes it works and sometimes it establishes just some connections e.g. 17 of 30.
  I saw similar problems by googling but nobody provided their solution. Thanks!
  Stack trace:</p>
  
  <pre><code>javax.naming.ServiceUnavailableException: 172.16.0.xxx:389; socket closed
  at com.sun.jndi.ldap.Connection.readReply(Connection.java:464)
  at com.sun.jndi.ldap.LdapClient.ldapBind(LdapClient.java:370)
  at com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:222)
  at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2752)
  at com.sun.jndi.ldap.LdapCtx.&lt;init&gt;(LdapCtx.java:328)
  at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:205)
  at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:223)
  at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:166)
  at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:96)
  at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:695)
  at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:318)
  at javax.naming.InitialContext.init(InitialContext.java:253)
  at javax.naming.InitialContext.&lt;init&gt;(InitialContext.java:227)
  at javax.naming.directory.InitialDirContext.&lt;init&gt;(InitialDirContext.java:112)
  </code></pre>
  
  <p>EDIT: some code</p>
  
  <pre><code>socket = new Socket(hostname, port);
  is = socket.getInputStream();
  os = socket.getOutputStream();
  bif = new BufferedInputStream(is);
  bof = new BufferedOutputStream(os);
  
  env = new Hashtable&lt;String, String&gt;();
  env.put(Context.SECURITY_AUTHENTICATION, "simple");
  env.put(Context.SECURITY_PRINCIPAL, usr);
  env.put(Context.SECURITY_CREDENTIALS, pwd);
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.REFERRAL,"follow");
  env.put("java.naming.ldap.derefAliases", "never");
  env.put(Context.PROVIDER_URL, "ldap:// /*address*/);
  try {
      ctx = new InitialDirContext(env);//ERROR
  } catch (ServiceUnavailableException e1) {
      e1.printStackTrace();
      System.out.println("service unavailable");
  }
  </code></pre>