在“无限”循环线程中运行代理是错误的吗?

时间:2012-04-10 14:33:11

标签: java multithreading

我有一个网络爬虫,其基本布局是一个管理器,它运行打开连接的代理,获取内容并将其插入数据库。

这些代理中的每一个都在循环中的单独线程中运行,直到用户发送停止信号。这些代理从经理代理处获取任务。

问题是如果代理中发生异常,则不能将其抛出到接口(除非我使用某个观察者来发出异常信号)。

我认为这种设计是错误的,正确的是创建一个有限的任务并将它们放在Executor中(为每个URL创建一个任务来打开连接,获取内容或插入数据库)。

我说我当前的设计错了,必须改变布局吗?什么是多线程使用的正确布局,其中不同的代理执行不同的工作部分?

1 个答案:

答案 0 :(得分:4)

是的,我认为您应该使用Executors。如果您提交Callable类,则可以从您的蜘蛛代理中抛出并检查返回的Future,这会导致异常被抛出到作业提交者,以便将其记录或显示到您的UI。

ExecutorService pool = Executors.newFixedThreadPool(10);
Future<Void> future = pool.submit(new Callable<Void>() {
    public Void call() throws Exception {
       // your agent code goes here
       // this can throw an exception in this block which will be re-thrown below
       return null;
    }
});
...
try {
   // then the exception will be thrown here for you to catch and log
   future.get();
} catch (ExecutionException e) {
   // log the e.getCause() here
}
...
pool.shutdown();