今天的任务是解决Client类,它在源码的ipc包下,作为分布式C-S结构的C。本文的前提是你要了解C的功能。本文使用的源码是hadoop-0.10.1。start!
在它的里面包括5个子类,分别是:
Call:
Connection:
ParallelCall:
ParallelResult:
ConnectionCuller:
下面我们依次分析这五个类的内容:
Call:
这个类是一次调用过程的一个封装,它的成员变量如下所示:
int id; // call id
Writable param; // parameter
Writable value; // value, null if error
RemoteException error; // error, null if value
long lastActivity; // time of last i/o
boolean done; // true when call is done
可以看出,这里面包括了调用的参数,返回的结果以及一些相关的属性。在他的方法中,值得一提的就是callComplete方法。这个方法调用了自身的notify,从而使因它阻塞的类被唤醒而继续进行后面的工作(在此只是大概地形容,具体的关于wait和notify的内容请参见第一篇)。
那么这个类的功能和生命周期是什么样的呢?接下来我们直接来到Client类的call方法,具体的代码如下:
/**
* Make a call, passing <code>param</code>, to the IPC server running at
* <code>address</code>, returning the value. Throws exceptions if there are
* network problems or if the remote code threw an exception.
*/
public Writable call(Writable param, InetSocketAddress address)
throws IOException {
Connection connection = getConnection(address);
Call call = new Call(param);
synchronized (call) {
connection.sendParam(call); // send the parameter
long wait = timeout;
do {
try {
call.wait(wait); // wait for the result
} catch (InterruptedException e) {
}
wait = timeout
- (System.currentTimeMillis() - call.lastActivity);
} while (!call.done && wait > 0);
if (call.error != null) {
throw call.error;
} else if (!call.done) {
throw new SocketTimeoutException(
"timed out waiting for rpc response");
} else {
return call.value;
}
}
}
我们看到,这个方法要做的工作是发起一个调用并获得相应的返回(无论正确与否)。当这个方法调用后,一个Call的对象建立,然后将Call通过Connnection发出(Connection的问题后面再说),然后这段代码就进入了等待的状态(call.wait(duration)),直到时间到达或者被notify。这样我们就大概明白了整个Call的过程:
(1)Client创建Call并填充相应的参数;
(2)Client把Call交给Connection进行监控处理,而自己进入wait状态
(3)当满足了等待的结束条件,Client将相应的后续任务处理并完成这次调用。
(思考:call是本地线程创建的一个变量,为什么要做同步?)
那么我们就知道了这个流程,实际上Client与Server的交互也就是这个流程,那么我们现在缺少了一个关键的流程,就是Connection,下面我们来看Connection。
Connection
首先是它的成员变量:
private InetSocketAddress address; // address of server
private Socket socket = null; // connected socket
private DataInputStream in;
private DataOutputStream out;
private Hashtable calls = new Hashtable(); // currently active calls
private Call readingCall;
private Call writingCall;
private int inUse = 0;
private long lastActivity = 0;
private boolean shouldCloseConnection = false;
前面四个变量都是和网络连接相关的变量,而第五个变量在原代码中没有做泛型,所以一下子猜不出来,但是大概可以知道它是做连接