3 Replies Latest reply: Aug 10, 2013 11:31 AM by 800839 RSS

    Singleton for LDAP DirContext




      I want to create a singleton for DirContext for LDAP configuration, hence i have used the initialize on demand
      class holder idiom as shown below

      public class SlmApplicationContext {

           * inner class to hold the instance.
          private static class Holder {
              private static DirContext instance =
                  new InitialDirContext();

           * Method to get the singleton instance of this class.
           * @return SlmApplicationContext
          public static SlmApplicationContext getInstance() {
              return Holder.instance;
          Now the problem is if i close the DirContext.close(), when the next request comes the singleton wont
          work as the dir context is already closed, hence it will create a new dir context for each requests.
          Which breaks the singleton concept, hence how we can ensure the  singleton works fine even with DirContext.close()?
          Please clarify.

        • 1. Re: Singleton for LDAP DirContext

          If you want a SINGLE, predefined and instantiated, DirContext THROUGHOUT the life of the program, then you CANNOT close it.

          • 2. Re: Singleton for LDAP DirContext

            I suppose you can define an interface that declares all the functions of DirContext except close().  GetInstance() will be changed to return the interface name, where all users of your program will use the interface name. This way, users will not have direct access to close(). Note you will need another (public) function in your class SimApplicationContext called something like close() so you (not the users) can close it at the appropriate time.


            On a side note: There is no need to specify '@return SlmApplicationContext' in your javadoc since its obvious from the function signature.

            Also, in addition to javadoc on the functions, I like to put javadoc on the class name too (assuming you don't already have it) since no one will know what class SlmApplicationContext is for. Lastly, if DirContext is closed and someone tries to use it, I suspect it will throw an exception rather than instansiate a new one.

            • 3. Re: Singleton for LDAP DirContext

              Thanks. Guys could you please share a snippet of how we can achieve the same without close()?