Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to synchonized this lambda statement?

Java / JDK 19. How to synchonized this lambda statement?

package sybex.ch00.exercies;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class Q03 {

    public static void main(String[] args) {
        List<Integer> data = new ArrayList<>();
        IntStream.range(0, 100).parallel().forEach(s -> data.add(s));
        System.out.println(data.size());
    }
}

I read book, they said after synchronized lamba will make thread safe, and return 100, but I don’t know how to do. Please guide me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No special trick to it, just use a synchronized block:

public class Q03 {

    public static void main(String[] args) {
        List<Integer> data = new ArrayList<>();
        IntStream.range(0, 100).parallel().forEach(s -> {
            synchronized(data) { data.add(s); }
        });
        System.out.println(data.size());
    }
}

Depending on the context you are running this in you will have to choose what object to synchronize on. Here data is a good choice, or you could create an object to lock on:

public class Q03 {

    public static void main(String[] args) {
        List<Integer> data = new ArrayList<>();
        Object lock = new Object();
        IntStream.range(0, 100).parallel().forEach(s -> {
            synchronized(lock) { data.add(s); }
        });
        System.out.println(data.size());
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading