CommunicationException [Root exception is ConnectException: Connection timed out]

Karthik Bose picture Karthik Bose · May 7, 2013 · Viewed 27.1k times · Source

I'm getting this exception occasionally, while trying to connect Active Directory.

javax.naming.CommunicationException: <ServerIP>:<PORT> 
  [Root exception is java.net.ConnectException: Connection timed out: connect]

Here is my code:

    DirContext ctx = null;
    Properties env = new Properties();

    env.put(Context.SECURITY_PRINCIPAL, <Bind_USER>);
    env.put(Context.SECURITY_CREDENTIALS, <Bind_USER_PWD>);
    env.put(Context.PROVIDER_URL, "ldap://<ServerIP>:<PORT>");            
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    ctx = new InitialDirContext(env);

Getting the connection timeout exception in this line ctx = new InitialDirContext(env);. It doesn't happen every-time, but happens quite often.

Please advise me, how to get rid of this issue?

Answer

Tamara Aviv picture Tamara Aviv · Aug 17, 2016

This happens to me occasionally as well. And because it only happens ~1% of the time, I doubt it's any of the reasons listed in Juned's answer since nothing changes in my setting.

For me it happens quite randomly and is fixed without any specific action on my part. This makes me believe that the answer provided here is correct:

It is most likely a connection leak. Connection timeout can be caused by many things but most of them would cause it every time. Very likely the LDAP server has a maximum number of connections it will handle simultaneously, and beyond that it won't call accept(), so new incoming connections remain in the backlog queue, which fills up, which can cause further incoming connections to time out.

@OP Can you run netstat -anp at the server when this happens, to check the hypothesis above? Can you also set a connection-idle timeout at the LDAP server? That would fix connection leaks but in a brute-force way that may break other things.