NamingEnumeration hasMoreElements method takes a lot of time when returning false for LDAP

ldap

Solution

The `NamingEnumeration` does some cleanup when calling `hasMoreElements()` the last time. It also checks if there are additional referrals is the context-property `Context.REFERRAL` is set to "follow". In one case in our software this caused exactly the behaviour as described: The last call to `hasMoreElements()` (or to `hasMore()` or calling `next()` more often than allowed) caused up to 40 seconds as referrals are searched in the LDAP context. The solution is to not set `Context.REFERRAL` to "follow".

Problem

I am trying to search a LDAP server(Active Directory). When I parse the search results, the `hasMoreElements` method of `NamingEnumeration` takes around 15-20 seconds to execute when it returns false. It is not the case when it is returning true. Is there a way to solve this issue? Code: ``` SearchControls ctrl = new SearchControls(); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectClass=user("uid"="abc"))"; NamingEnumeration ne = dirContext.search("ldap://abc:389/dc=abc,dc=xy", searchFilter,ctrl); if (ne != null) { while (ne.hasMoreElements()) { //parse results } ```

Original source