【问题标题】:Is Java fork/join (divide and conquor) possible when inserting line-by-line into MongoDB from InputStream?从InputStream逐行插入MongoDB时,Java fork/join(分而治之)是否可行?
【发布时间】:2014-07-27 12:26:21
【问题描述】:

我在下面列出了对 MongoDB 执行批量插入的代码。这段代码需要很长时间才能运行——插入 2000 万个 Mongo 文档大约需要一个小时。

代码的耗时部分--scanner.hasNextLine()--nextLine()--插入循环--有时运行慢到 20 秒一次迭代。我注意到,这种缓慢在工作进行到一半时变得很明显。 (这个论坛上的答案表明,mongo insert-batch 或 regular 可能很昂贵,因为将 json 转换为二进制格式 bson。)

我想加快这个过程。我想在几个核心上并行处理这项工作。我可以使用 Fork/join 执行此操作吗?我之所以问,是因为我看不到如何在此代码的情况下应用分而治之的策略,其 while 循环在输入流上。

另一种可能是使用 ThreadPoolExecutor。最好使用执行人吗?执行者会在多个核心上分配作业吗?

代码:

Scanner lineScan = new Scanner(inputStream, encoding);
while (lineScan.hasNextLine() {
  //add to list of DBObjects to be inserted as a batch
  //do batch insert here if object-count threshold is reached.
}

使用 ThreadPoolExecutor 的类似代码(参见

Java Iterator ConcurrencyJava: Concurrent reads on an InputStream):

ExecutorService executor = Executors.newCachedThreadPool();
Iterator<Long> i = getUserIDs();
while (i.hasNext()) {
    final Long l = i.next();

    Runnable task = new Runnable() {
        public void run() {
            someObject.doSomething(l);
            anotheObject.doSomething(l);
        }
    }

    executor.submit(task);
}

executor.shutdown();

任何关于哪种技术可以最好地加速此循环和插入的观点将不胜感激。 非常感谢!

【问题讨论】:

    标签: java multithreading mongodb parallel-processing threadpoolexecutor


    【解决方案1】:

    您应该考虑 2.12 驱动程序中的批量写入操作:http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#bulk-operations。此外,在插入期间禁用索引也会有所帮助。

    【讨论】:

    • 谢谢,我想知道关于 mongo 的文章。另外,我应该在我的伪代码中添加索引是在所有插入完成后添加的,所以我认为它们不是问题。
    猜你喜欢
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2019-11-05
    • 2013-11-09
    • 2021-08-31
    • 2014-04-28
    相关资源
    最近更新 更多