LDAP connection issue

Problem1:

Sometimes we can not get LDAP connection from LDAP server.

Cause1:
We can not close LDAP connection when program is end.

Solution1-1(don't do that):


Currently our code to close LDAP connection are as below,

LdapContext cladptx = null;
NamingEnumeration<?> results = null;
try {
cladptx = createConnection();
results = cladptx.search(ldapConnector.getEntry(), filter, constraints); } catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (cladptx != null) {
cladptx.close();
}
} catch (Exception e2) {
logger.error(e2.getMessage(), e2);
}
}

But actually LDAP connection was not closed completely.

Solution1-2(Good solution):

We need to close various parameters of context and NamingEnumeration.Code as below,

LdapContext cladptx = null;
NamingEnumeration<?> results = null;
try {
cladptx = createConnection();
results = cladptx.search(ldapConnector.getEntry(), filter, constraints);

} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
if(results!=null) {
results.close();
}
if (cladptx != null) {
cladptx.close();
}
} catch (Exception e2) {
logger.error(e2.getMessage(), e2);
}
}

Problem2:

After I closed various parameters and ran a test which loops 4000 times on a LDAP client application, I observed the following errors in Windows Operating System when the load increased beyond a certain threshold:

    javax.naming.CommunicationException: localhost:10389 [Root exception is java.net.BindException: Address already in use: connect]
    at com.sun.jndi.ldap.Connection.<init>(Connection.java:210)
    at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:118)
    </init></init>

Cause2:

The causes for the errors are that the dynamic ports in the OS are running out so that client application can not make any more connections to LDAP server.
Usually LDAP server is running on a specific port (say 10389) and when a connection is created from client, that is assigned a port in the range of dynamic ports which is defined as a property of Windows OS. This issue is not visible on Linux.

So the above errors can occur when no available ports are left.

Solution2:

We'd better use connection pool to solve this problem.See below code,

InitialDirContext context = null;
try {
System.setProperty("com.sun.jndi.ldap.connect.pool.maxsize", "50");
Hashtable<String,String> env = new Hashtable<String,String>();
//env.put("com.sun.jndi.ldap.connect.pool", "true");
context = new InitialDirContext(env);
} catch (NamingException e) {
logger.error(e.getMessage(),e);
}

Conclusion
1. Enable LDAP connection pooling when creating the connection to the LDAP..
2. Close all sub Contexts and NamingEnumerations derived from a particular LDAP connection Context, close them explicitly at the end of their usage.

你可能感兴趣的:(Connection)