【问题标题】:Split one large file into multiple InputStream(s) to be processed in multithreading in Java将一个大文件拆分为多个 InputStream(s) 以在 Java 中进行多线程处理
【发布时间】:2019-01-05 02:11:37
【问题描述】:

我的代码:

public ArrayList<InputStream> getAllInputStreams() {
    ArrayList<InputStream> allStreams = new ArrayList<InputStream>();
    InputStream stream = this.getNext();
    while (stream != null) {
        allStreams.add(stream);
        stream = this.getNext();
    }
    return allStreams;
}

public InputStream getNext() {
    if (done()) {
        return null;
    }
    InputStream segment = createInputStream();
    this.countStream++;
    return segment;
}

protected InputStream createInputStream() {
    BoundedInputStream res = new BoundedInputStream(
            Channels.newInputStream(this.randomAccessFile.getChannel().position(this.countStream * chunkSize)), chunkSize);
    res.setPropagateClose(false) ;
    return res ;
}

我正在尝试将file 拆分为多个 InputStream(s) (private RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");。所有 InputStream(s) (来自getAllInputStreams()) 以由多个线程处理,似乎它们中的大多数都是空的。为什么?

欢迎任何提示。谢谢

更新

以下代码似乎工作正常。下面的一段代码是将文件分成几个夹头的好方法吗?每个卡盘的大小应该小于内存大小吗?

protected InputStream createInputStream() {
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
    BoundedInputStream res = new BoundedInputStream(
            Channels.newInputStream(randomAccessFile.getChannel().position(this.countStream * chunkSize)), chunkSize);
    res.setPropagateClose(false) ;
    return res ;
}

【问题讨论】:

  • if (done()) { return null; 因为大部分都“完成”了?真的,我看不出我们如何从您显示的代码中分辨出来。
  • 是什么让您认为使用从同一 IO 设备读取的多个流,只是在不同的位置会加速事情?根据底层硬件和软件堆栈,您实际上可能会看到速度变慢。因为您对相同 IO 设备的真正随机读取访问会产生大量开销。
  • @GhostCat,那么,有什么办法可以加快速度吗?谢谢

标签: java multithreading file inputstream


【解决方案1】:

我认为这种说法:

      res.setPropagateClose(false);

在您的“更新”解决方案中会导致资源泄漏。您打开的 RAF 不与其他任何东西共享。当 BoundedInputStream 关闭时,您需要关闭以传播到 RAF。

【讨论】:

    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 2021-03-04
    • 2021-03-17
    • 2016-07-26
    相关资源
    最近更新 更多