我的代码检查给定代理是否正常工作并返回类型。在我检查代理是否为HTTP的函数中,如果代理已死,Socket.Connect方法不会抛出任何异常。 此函数由CachedThreadPool中的ExecutorService执行。 这是功能:
private CheckResponse checkHttp(MyProxy p) {
try {
SocketAddress addr = new InetSocketAddress(p.getIp(), p.getPort());
Proxy proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, addr);
Socket socket = new Socket(proxy);
long startTime = System.currentTimeMillis();
socket.connect(ProxyChecker.dest, Data.CHECK_TIMEOUT);
long elapsedTime = System.currentTimeMillis() - startTime;
socket.close();
return new CheckResponse(false, elapsedTime);
} catch (Exception e) {
e.printStackTrace();
return new CheckResponse(true, 0);
}
}
调试我发现程序在socket.connect方法之后进入ThreadPoolExecutor类的runWorker方法并永远循环。
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
没有抛出异常,我无法解决问题。为什么呢?