ycomp ycomp - 5 months ago 10
Java Question

Why can't this stream run in parallel?

How do I get this to run in parallel? my output is totally sequential and elapsed time is not displayed until everything is finished. This is my first attempt at parallelizing streams so I'm probably missing something obvious to everyone else. But I can't see what is wrong compared to sample code I looked at.

public class Paralells {


void run() {
for (int i = 1; i<=1000; i++) System.out.println(i);
}


public static void main(String[] args) {

ArrayList<Paralells> a = new ArrayList();

a.add(new Paralells());
a.add(new Paralells());
a.add(new Paralells());
a.add(new Paralells());
a.add(new Paralells());

long x = System.currentTimeMillis();
a.parallelStream().forEach(p -> p.run());
System.out.println("ELAPSED: " + (System.currentTimeMillis()-x));
}

}

Answer

But it is parallel! Experiment this:

import java.util.*;
public class Paralells {

    private int id;
    public Paralells(int id) { this.id = id; }
    void run() {
        for (int i = 1; i<=1000; i++) System.out.println(id+" "+i);
    }


    public static void main(String[] args) {

        ArrayList<Paralells> a = new ArrayList();

        a.add(new Paralells(1));
        a.add(new Paralells(2));
        a.add(new Paralells(3));
        a.add(new Paralells(4));
        a.add(new Paralells(5));

        long x = System.currentTimeMillis();
        a.parallelStream().forEach(p -> p.run());
        //a.forEach(p -> p.run()); // sequential
        System.out.println("ELAPSED: " + (System.currentTimeMillis()-x));
    }
}

An id is set for each element and is used while printing messages. You should be able to observe that the messages are interlaced. Compare with the sequential version (uncomment the appropriate line and comment the parallel version).

Of course, time is collected after everything finished. Time is printed after forEach...

Comments