成都游戏学院 http://www.cdgamecollege.org
电话:028-85586115
sendRequestAsynch是异步的API。这个是写作过程中的一个版本。在review之后发现其中存在同步问题。synchronized
(request)不是在启动孙子线程tt之后执行。问题在于如果sendRequest(request)在执行到最后是发送request.notifyAll()时,可能还没有执行synchronized (request)
。这样就存在request.wait(timeout)不会被唤醒而超时的问题。
应当把sendRequest(request) 放到同步块中。改正后的代码:
exception的处理还没有规范起来。许多细节还待完善(post还没有被支持),... 有任何问题都欢迎指出。
public void sendRequestAsynch(final NetworkRequest request, final long timeout) throws Exception {
Thread t = new Thread() {
public void run() {
try {
log.debug("send request in another thread.");
Thread tt = new Thread() {
public void run() {
try {
log.debug("send request in grandson thread. " + request.getSequenceId());
sendRequest(request);
}catch (Exception e) {
log.warn(e.getMessage());
}
}
};
tt.start();
synchronized (request) {
log.debug("Try to wait for " + timeout + " " + request.getSequenceId());
request.wait(timeout);
if (request.isDelayed()) {
queue.removeElement(request);
timeoutQueue.addElement(request);
log.debug("Request TIMEOUT !!!!!!!!!!!!!!!!");
log.debug("Stop the network request thread for the timeout.");
}else {
log.debug("Be Notified and wakeup.");
}
}
}catch (Exception e) {
log.warn(e.getMessage());
}
log.debug("Exit the thread.");
}
};
t.start();
}
应当把sendRequest(request) 放到同步块中。改正后的代码:
public void sendRequestAsynch(final NetworkRequest request, final long timeout) throws Exception {
Thread t = new Thread() {
public void run() {
try {
log.debug("send request in another thread.");
synchronized (request) {
Thread tt = new Thread() {
public void run() {
try {
log.debug("send request in grandson thread. " + request.getSequenceId());
sendRequest(request);
}catch (Exception e) {
log.warn(e.getMessage());
}
}
};
tt.start();
log.debug("Try to wait for " + timeout + " " + request.getSequenceId());
request.wait(timeout);
if (request.isDelayed()) {
queue.removeElement(request);
timeoutQueue.addElement(request);
log.debug("Request TIMEOUT !!!!!!!!!!!!!!!!");
log.debug("Stop the network request thread for the timeout.");
}else {
log.debug("Be Notified and wakeup.");
}
}
}catch (Exception e) {
log.warn(e.getMessage());
}
log.debug("Exit the thread.");
}
};
t.start();
}
exception的处理还没有规范起来。许多细节还待完善(post还没有被支持),... 有任何问题都欢迎指出。
