Server.Handle"线程主要的任务是用于处理请求。考虑到可能同时有多个请求要处理,所以Handle一般不唯一。Handle线程循环从callQueue中取出一个call,根据调用Server.Call关联的连接Server.Connection所对应的用户Subject,来执行IPC调用过程。然后将处理结果序列化到call并加入到call对应的connection中的responseQueue【responseQueue也是一个Call集合,每个connection都有一个responseQueue,保存了给对应的client的响应信息】:
/** Handles queued calls . */
private class Handler extends Thread {
public Handler(int instanceNumber) {
this.setDaemon(true);
this.setName("IPC Server handler "+ instanceNumber + " on " + port);
}
@Override
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);// 设置当前处理线程的本地变量的拷贝
ByteArrayOutputStream buf = new ByteArrayOutputStream(10240);
while (running) {
try {
final Call call = callQueue.take(); // pop the queue; maybe blocked here
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": has #" + call.id + " from " +
call.connection);
String errorClass = null;
String error = null;
Writable value = null;
CurCall.set(call);// 设置当前线程本地变量拷贝的值为出队得到的一个call调用实例
try {
// Make the call as the user via Subject.doAs, thus associating
// the call with the Subject
// // 根据调用Server.Call关联的连接Server.Connection所对应的用户Subject,来执行IPC调用过程
value =
Subject.doAs(call.connection.user,
new PrivilegedExceptionAction<Writable>() {
@Override
public Writable run() throws Exception {
// make the call
return call(call.connection.protocol,
call.param, call.timestamp);
}
}
);
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
LOG.info(getName()+", call "+call+": error: " + e, e);
errorClass = e.getClass().getName();
error = StringUtils.stringifyException(e);
} catch (Throwable e) {
LOG.info(getName()+", call "+call+": error: " + e, e);
errorClass = e.getClass().getName();
error = StringUtils.stringifyException(e);
}
CurCall.set(null); // 当前Handler线程处理完成一个调用call,回收当前线程的局部变量拷贝
// 处理当前获取到的调用的响应
setupResponse(buf, call,
(error == null) ? Status.SUCCESS : Status.ERROR,
value, errorClass, error);//将处理的结果序列化到call中
responder.doRespond(call); // 将调用call加入到响应队列中,等待客户端读取响应信息
} catch (InterruptedException e) {
if (running) { // unexpected -- log it
LOG.info(getName() + " caught: " +
StringUtils.stringifyException(e));
}
} catch (Exception e) {
LOG.info(getName() + " caught: " +
StringUtils.stringifyException(e));
}
}
LOG.info(getName() + ": exiting");
}
}
void doRespond(Call call) throws IOException {
synchronized (call.connection.responseQueue) {
call.connection.responseQueue.addLast(call);//将call加入到call对应的connection对应的responseQueue中
if (call.connection.responseQueue.size() == 1) {//当入队前队列为空时,则调用processResponse将为call.connection对应的通道添加写事件,同时将call附加到通道上。这使得在Responder.run调用doAsyncWrite时可以通过选择键获得附加对象call。
processResponse(call.connection.responseQueue, true);
}
}
}
