<分区>
我需要在虚拟机中写入很多文件。我需要编写大约 300.000 个文件,今天生成文件的工作很好,但使用的时间是 3~4 小时才能完成工作。
如何实现这个并行线程?
<分区>
我需要在虚拟机中写入很多文件。我需要编写大约 300.000 个文件,今天生成文件的工作很好,但使用的时间是 3~4 小时才能完成工作。
如何实现这个并行线程?
最佳答案
我已经找到了一种方法,您可以从多线程中获益,但对代码的更改最少。
import java.io.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by peter.lawrey on 30/01/15.
*/
public class ConcurrentFileWriter {
private final ThreadPoolExecutor es;
private final int maxQueueSize;
public ConcurrentFileWriter() {
this(4, 10000);
}
public ConcurrentFileWriter(int concurrency, int maxQueueSize) {
this.maxQueueSize = maxQueueSize;
es = (ThreadPoolExecutor) Executors.newFixedThreadPool(concurrency);
}
public OutputStream newFileOutputStream(final String filename) {
return new ByteArrayOutputStream() {
@Override
public void close() throws IOException {
super.close();
final ByteArrayOutputStream baos = this;
if (es.getQueue().size() > maxQueueSize)
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new AssertionError(e);
}
es.submit(new Runnable() {
public void run() {
try {
FileOutputStream fos = new FileOutputStream(filename);
fos.write(baos.toByteArray());
fos.close();
} catch (IOException ioe) {
System.err.println("Unable to write to " + filename);
ioe.printStackTrace();
}
}
});
}
};
}
public PrintWriter newPrintWriter(String filename) {
try {
return new PrintWriter(new OutputStreamWriter(newFileOutputStream(filename), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
public void close() {
es.shutdown();
try {
es.awaitTermination(2, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
public static void main(String... args) {
long start = System.nanoTime();
ConcurrentFileWriter cfw = new ConcurrentFileWriter();
int files = 10000;
for (int i = 0; i < files; i++) {
PrintWriter pw = cfw.newPrintWriter("file-" + i);
pw.println("Hello World");
pw.close();
}
long mid = System.nanoTime();
System.out.println("Waiting for files to be written");
cfw.close();
long end = System.nanoTime();
System.out.printf("Took %.3f seconds to generate %,d files and %.3f seconds to write them to disk%n",
(mid - start) / 1e9, files, (end - mid) / 1e9);
}
}
在 SSD 上,打印
Waiting for files to be written
Took 0.075 seconds to generate 10,000 files and 0.058 seconds to write them to disk
这样做的目的是让您像现在一样编写单线程代码,但是实际写入磁盘是作为后台任务完成的。
注意:您必须调用 close() 来等待文件真正写入磁盘。
写入大量文件的问题在于,这对 HDD 来说是一项繁重的工作。使用多线程不会使您的驱动器旋转得更快。每次打开和关闭一个文件时,它使用大约 2 个 IO(IO 操作)如果你有一个 HDD 并且它支持 80 IOPS(每秒 IO),你每秒可以打开和关闭 40 个文件。即 300,000 个文件大约需要 2 小时。
相比之下,如果您使用 SSD,您可以获得 80,000 IOPS,速度提高 1000 倍,而且您打开和关闭文件可能只需要 8 秒。
一旦您切换到 SSD,可能值得使用多线程。一种简单的方法是使用 Java 8 中的 Stream API。
你可以这样做
IntStream.range(0, 300000).parallel().
.forEach(i -> createFile(i));
关于java - 使用多线程写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28236742/