Better way to loop in parallel

Viewed 108

If I want to parallelize this code:

try {
    for (int i = 0; i < 10000; i++) {
        new File(String.valueOf(i)).createNewFile();
    }
} catch (IOException e) {
    e.printStackTrace();
}

then I rewrite it to:

ArrayList<String> fileNames = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
    fileNames.add(String.valueOf(i));
}
fileNames.parallelStream().forEach(i -> new File(i).createNewFile());

But isn't there a better (simpler) way for that?

3 Answers

A distinct non-answer:

If I want to parallelize this code:

Then you would (most likely) need to turn to a completely different hardware/software stack to gain anything from doing so.

You see, unless we are talking about some sort of "remote" file system, that can be (and actually is) reached via multiple "paths", and that actually resembles multiple IO devices ... your attempt of optimisation is pointless.

It only makes sense to parallelize activities that include a lot of waiting for different things. But in your case, your code talks to one operating system, using one file system. Most likely, your idea is even slowing down things.

Try IntStream in parallel():

IntStream.range(0, 10000).parallel().forEach(i -> {
    try {
        new File(String.valueOf(i)).createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
});

But it won't be much efficient because of the disk operations.

just to have another possibility..

fileNames.parallelStream().map(Path::Files.createFile).collect(Collectors.toList());
fileNames.stream().map(path -> Files.createFile(path)).collect(...

between returns a list with objects Path inside.

Related