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.
>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());
}
}