简体   繁体   中英

Java 8 parallelStream mechanics

Is there a way to process each class attribute in parallel using java 8 lambda?

For example, for a given Car.java:

public class Car{
    private String color;
    private String model;
    private float value;
    private float tax;
    // and others attributes
    .
    .
    .
    // Getters and Setters
}

I would like to make some process over color, model, value, tax, etc in parallel. So basically the wished logic would be:

parallel processing:
    - color
    - model
    - value
    - tax

then join and update Car.java object instance fields. 

Please, note that this problem is independent of the number of cars instances. It could be just one or many.

I was curious, how that would look like. Assuming the restriction holds, that the processing of each of the properties is independent of one another, that would be one way to utilize parallelStream() . But I doubt very much, that this pays off due to the overhead of the parallel machinery. One could make it even more outlandish using reactive streams , eg RxJava.

public class Car{
    public String color;
    public String model;
    public float value;
    public float tax;

    public Car(String color, String model, float value, float tax) {
        this.color = color;
        this.model = model;
        this.value = value;
        this.tax = tax;
    }

    @Override
    public String toString() {
        return "Car{" +
                "color='" + color + '\'' +
                ", model='" + model + '\'' +
                ", value=" + value +
                ", tax=" + tax +
                '}';
    }
}

@Test
public void process() {
    List<Consumer<Car>> processors = Arrays.asList(
            c -> c.color = printThread(c.color.toLowerCase()),
            c -> c.model = printThread(c.model.toLowerCase()),
            c -> c.value = printThread(c.value * c.value),
            c -> c.tax = printThread(c.tax / c.tax));

    Arrays.asList(new Car("Red", "AlphaGorilla", 1f, 0.5f), new Car("Blue", "Bloated++", 10f, 0.2f))
            .parallelStream().forEach(c -> {
        System.out.println(c);
        processors.parallelStream().forEach(p -> {
            p.accept(c);
            fakeExpensiveComputation();
        });
        System.out.println(c);
    });
}

private <T> T printThread(T smthg) {
    System.out.println(String.format("Calculated value %s in thread %d", smthg.toString(), Thread.currentThread().getId()));
    return smthg;
}

private void fakeExpensiveComputation() {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        throw new RuntimeException();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM