0 Replies Latest reply on Jan 30, 2017 4:52 AM by Luc De Kesel

    Singleton Timer bean

    Luc De Kesel Newbie

      Hi all,

       

      I have a singleton timer bean that is used to evict expired entries from a cache. The scheduled method of the timer bean accesses a common hashmap holding the entries. If the timestamp of the entry is too old, it is removed from the hashmap.

      The cache object is encapsulated in the LocalAuthenticator class (HashMap<String,String>).

       

      On the other hand, entries are added, removed and updated from user threads (JAX-RS controllers) uniquely through methods of the LocalAuthenticator.

      Can I use the lock of the LocalAuthenticator to synchronize access ? No point in synchronizing the bean method since this method (evictSessions) is only called from the timer.

      Can I simply use synchronized  on the LocalAuthenticator methods ?

       

       

      /**
       * Session management for REST API <br/>
       *
       */
      @Singleton
      @Startup
      @ConcurrencyManagement(ConcurrencyManagementType.BEAN)
      public class SessionTimerBean {
        private static final Logger logger = LogManager.getLogger(SessionTimerBean.class);
        LocalAuthenticator localAuthenticator;
        private long sessionTimeout;
        public SessionTimerBean() throws Exception {
        this.localAuthenticator = LocalAuthenticator.getInstance();
        this.sessionTimeout = BeanLocator.getInstance().getSessionConfig().getSessionTimeout() * DateTools.MILLIS_IN_ONE_MINUTE;
        logger.debug("Create session cleanup timer with timeout {} milliseconds", this.sessionTimeout);
        }
      
        @Schedule(hour="*", minute="*", persistent=false)
        public void evictSessions() {
      
             List<String> tokens = this.localAuthenticator.getSessionKeys();
             long timestamp = System.currentTimeMillis();
      
             for (String token: tokens) {
                  LBSSession session = this.localAuthenticator.getSession(token);
                  if (session != null) {
                  if (timestamp - session.getModified() > this.sessionTimeout) {
                       this.localAuthenticator.evictSession(session.getToken());
                  }
             }
        }
      
        }
      }
      

       

      Thank you.