You need to enable JavaScript to run this app. 为何用ExecutorService抓取论坛帖子时返回19帖而非预期1帖?Bug在哪?
优惠活动
大模型
产品
解决方案
定价
更多

为何用ExecutorService抓取论坛帖子时返回19帖而非预期1帖?Bug在哪?

抓取结果数量异常的问题定位与修复

问题根因

代码存在3个直接导致返回帖子数量远高于预期的问题,刚好能解释为什么预期返回1条、实际返回19条的异常:

  • 核心笔误:线程任务内的遍历逻辑存在索引错用的问题。提交到线程池的Lambda代码中,循环遍历posts集合时本应使用循环变量j取对应元素,实际却错误使用了页码变量finalI:
    错误代码行:postList.add(createNewPost(posts.get(finalI), thread, finalJ));
    这行代码会导致不管循环遍历到j的哪个位置,每次add操作取的都是索引固定为finalI的单条帖子,循环次数完全等于posts集合的元素个数。如果单页抓取到的.message-inner元素移除最后1个冗余节点后刚好剩19个,循环就会执行19次,往postList里塞入19条完全重复的相同帖子,直接造成结果数和预期不符。
  • 线程安全漏洞:多线程任务共享的postList是普通非线程安全的ArrayList,没有做任何并发保护,多线程同时写入时会出现元素重复、覆盖、数组越界等问题,进一步放大结果数的偏差。
  • 页码遍历逻辑错误:循环条件写为i < secondPage,如果要抓取firstPage到secondPage范围的所有页码,会漏掉secondPage对应的最后一页,比如要爬取1、2两页时,实际只会爬取第1页。

冗余与可优化点

  • 初始创建核心线程数为20的固定线程池完全没必要:不管实际需要爬几页,大部分线程都会长期闲置,造成资源浪费。
  • 代码中重复调用了两次executorService.shutdown(),属于无意义的冗余逻辑。
  • Jsoup页面抓取的逻辑放在循环外的单线程逻辑中,没有放入线程任务内部,既浪费了多线程的并发优势,也没有做抓取异常捕获,一旦网络波动、页面返回404,接口会直接抛出500错误。
  • 线程任务等待超时时间设置为100000秒,远超过实际业务需要的合理时长。

修复参考代码

@PostMapping("/search")
public String scrapPosts(@RequestParam(name = "thread", required = true) final String thread,
                         @RequestParam(name = "firstPage", required = true) final int firstPage,
                         @RequestParam(name = "secondPage", required = true) final int secondPage,
                         Model model) throws IOException {
    // 替换为线程安全的集合,避免多线程并发写入问题
    List<Post> postList = new CopyOnWriteArrayList<>();
    // 按服务器核心数设置线程池大小,避免创建过多闲置线程
    ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    // 修正循环边界,覆盖firstPage到secondPage的全范围页码
    for (int i = firstPage; i <= secondPage; i++) {
        int pageNum = i;
        // 把页面抓取、元素解析的逻辑移入线程任务,充分利用并发能力
        executorService.submit(() -> {
            try {
                Document doc = Jsoup.connect(thread + "page-" + pageNum).get();
                Elements posts = doc.getElementsByClass("message-inner");
                posts.remove(posts.size() - 1);
                // 修正元素取数的索引,使用循环变量j获取对应位置的帖子
                for (int j = 0; j < posts.size(); j++) {
                    postList.add(createNewPost(posts.get(j), thread, j));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    executorService.shutdown();
    try {
        // 调整为合理的30秒等待超时时间
        executorService.awaitTermination(30, TimeUnit.SECONDS);
        model.addAttribute("postList", postList);
    } catch (InterruptedException e) {
        System.out.println("任务等待超时");
        // 正确处理中断状态
        Thread.currentThread().interrupt();
    }
    return "search";
}

内容的提问来源于stack exchange,提问作者bwone12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.25 15:36:05