背景
Zookeeper中定义了SessionTracker
接口用于管理Session
实现
由于将会话管理的实现代码抽象为ExpiryQueue
,而ExpiryQueue
的分析见:https://blog.csdn.net/jpf254/article/details/80800626
SessionTrackerImpl
实现了SessionTracker
,同时也继承了Thread
,也是一个线程.其run()
与NIOServerCnxnFactory.ConnectionExpirerThread.run()
类似,代码如下:
@Override
public void run() {
try {
while (running) {
long waitTime = sessionExpiryQueue.getWaitTime();
if (waitTime > 0) {
Thread.sleep(waitTime);
continue;
}
for (SessionImpl s : sessionExpiryQueue.poll()) {
//1.标记会话状态为"closing"
setSessionClosing(s.sessionId);
//2.发起"会话关闭"请求
expirer.expire(s);
}
}
} catch (InterruptedException e) {
handleException(this.getName(), e);
}
LOG.info("SessionTrackerImpl exited loop!");
}
@Override
synchronized public void setSessionClosing(long sessionId) {
if (LOG.isTraceEnabled()) {
LOG.trace("Session closing: 0x" + Long.toHexString(sessionId));
}
SessionImpl s = sessionsById.get(sessionId);
if (s == null) {
return;
}
s.isClosing = true;
}
@Override
public void expire(Session session) {
long sessionId = session.getSessionId();
LOG.info("Expiring session 0x" + Long.toHexString(sessionId)
+ ", timeout of " + session.getTimeout() + "ms exceeded");
close(sessionId);
}