title: Singleton Object in Java Web service
body: <p>Good morning,
  I am currently developing a java web application that exposes a web service interface. In order to keep a global object in memory, I use the following class as a Singleton:</p>
  
  <pre><code>public class SingletonMap {
      private static final SingletonMap instance = new SingletonMap();
      private static HashMap couponMap = null;
      private static long creationTime;
  
      private SingletonMap() {
          creationTime = System.currentTimeMillis();
          couponMap = new HashMap();
      }
  
      public static synchronized SingletonMap getInstance() {
          return instance;
      }
  
      public static long getCreationTime() {
          return creationTime;
      }
  }
  </code></pre>
  
  <p>I am using the above class in order to have the same instance of the HashMap for all the threads of the web service. The Web service class that maintains the SingletonMap object is the following:</p>
  
  <pre><code>@WebService()
  public class ETL_WS {
      private String TOMCAT_TEMP_DIR;
      private final int BUFFER_SIZE = 10000000;
      private static SingletonMap couponMap;
      private static SingletonProductMap productCategoryMap;
      private String dbTable = "user_preferences";
  
      public ETL_WS() {
          Context context = null;
          try {
              context = (Context) new InitialContext().lookup("java:comp/env");
              this.TOMCAT_TEMP_DIR = (String) context.lookup("FILE_UPLOAD_TEMP_DIR");
          }catch(NamingException e) {
          System.err.println(e.getMessage());
      }
  
      public long getCouponMapCreationTime() {
          return couponMap.getCreationTime();
      }
  
  }
  </code></pre>
  
  <p>The reason i have the method getCouponMapCreationTime() is to check that all the threads of the web service are accessing the same object. Is the above approach correct? How about performance overheads? Do you think I need the Singleton properties, or could I just use a static HashMap for all the threads? If I use a static HashMap, is it going to be garbage collected in case no thread is active?</p>
  
  <p>Thank you for your time.</p>