关于 Spider 类 run 方法实现的疑问:什么不直接使用 final 修饰符 #421

Open
brianway opened this Issue Dec 14, 2016 · 0 comments

Projects

None yet

1 participant

@brianway
brianway commented Dec 14, 2016 edited

最近在研读 webmagic 的源码,其中对 Spiderrun() 方法里从调度器取 request 的部分有点疑惑:为什么在 while 循环中不直接使用 final Request request = scheduler.poll(this)?这样只需要一个局部变量。

而现在的代码是先Request request = scheduler.poll(this),然后在 else 分支里二次赋值 final Request requestFinal = request?,这个 while 循环是核心代码,岂不是每次循环都多了一个变量分配和回收?

不知道是刻意这样写的,有其它的考虑,还是说直接 final 更好?

源码节选如下:

while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) {
    Request request = scheduler.poll(this);
    if (request == null) {
        if (threadPool.getThreadAlive() == 0 && exitWhenComplete) {
            break;
        }
        // wait until new url added
        waitNewUrl();
    } else {
        final Request requestFinal = request;
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    processRequest(requestFinal);
                    onSuccess(requestFinal);
                } catch (Exception e) {
                    onError(requestFinal);
                    logger.error("process request " + requestFinal + " error", e);
                } finally {
                    pageCount.incrementAndGet();
                    signalNewUrl();
                }
            }
        });
    }
}
@brianway brianway changed the title from 关于 Sprider 类 run 方法实现的疑问:什么不直接使用 final 修饰符 to 关于 Spider 类 run 方法实现的疑问:什么不直接使用 final 修饰符 Dec 14, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment