blackeyedcenter
blackeyedcenter

Reputation: 188

Better way to loop in parallel

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?

Upvotes: 3

Views: 114

Answers (3)

GhostCat
GhostCat

Reputation: 140641

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.

Upvotes: 3

ZaoTaoBao
ZaoTaoBao

Reputation: 2615

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.

Upvotes: 0

Mushif Ali Nawaz
Mushif Ali Nawaz

Reputation: 3866

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.

Upvotes: 1

Related Questions