在工作中遇到一个问题,为ExecutorServiceSessionValidationScheduler
定义了interval间隔时间,可几乎是过了2倍时间才会清理无效session,根本不准。
那是怎么回事呢?AbstractValidatingSessionManager#enableSessionValidation()
方法:
protected synchronized void enableSessionValidation() { SessionValidationScheduler scheduler = getSessionValidationScheduler(); if (scheduler == null) { scheduler = createSessionValidationScheduler(); setSessionValidationScheduler(scheduler); } // it is possible that that a scheduler was already created and set via 'setSessionValidationScheduler()' // but would not have been enabled/started yet if (!scheduler.isEnabled()) { if (log.isInfoEnabled()) { log.info("Enabling session validation scheduler..."); } scheduler.enableSessionValidation(); afterSessionValidationEnabled(); } }
它调用验证器的enableSessionValidation()
来启用验证器:
public void enableSessionValidation() { if (this.interval > 0l) { this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { private final AtomicInteger count = new AtomicInteger(1); public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); thread.setName(threadNamePrefix + count.getAndIncrement()); return thread; } }); this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS); } this.enabled = true; }
关键是这一行代码:
this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
它设定初始执行延迟与间隔时间一样,所以导致了第一次验证2倍时间的问题。