Thread-safe list

I'm scared of parallel processing

You should basically be careful about lists, but when it comes to parallel processing Be careful of multithreading

For example

No good.java


	private static List<String> list = new ArrayList<>();
	
	private static Consumer<Integer> qwe = v -> list.add(String.format("%s: %s", Instant.now(), v));
	
	public static void main(String[] args) {
		IntStream.range(0, 9).boxed().collect(Collectors.toList()).parallelStream().forEach(qwe);
		list.forEach(System.out::println);
	}

The result of this is

null
null
null
2019-11-08T17:37:22.279Z: 7
2019-11-08T17:37:22.313Z: 3
2019-11-08T17:37:22.313Z: 0
2019-11-08T17:37:22.313Z: 4
2019-11-08T17:37:22.313Z: 6
2019-11-08T17:37:22.313Z: 8

And

2019-11-08T17:37:48.381Z: 7
2019-11-08T17:37:48.381Z: 5
2019-11-08T17:37:48.381Z: 2
2019-11-08T17:37:48.416Z: 0
2019-11-08T17:37:48.416Z: 8
2019-11-08T17:37:48.417Z: 4
2019-11-08T17:37:48.417Z: 3
2019-11-08T17:37:48.417Z: 6

Or it's already messed up What is null w Trying to do it at the same time when adding to list I don't understand well and I'm having a disability.

So ...

This is okay.java


	private static List<String> list = Collections.synchronizedList(new ArrayList<>());
	
	private static Consumer<Integer> qwe = v -> list.add(String.format("%s: %s", Instant.now(), v));
	
	public static void main(String[] args) {
		IntStream.range(0, 9).boxed().collect(Collectors.toList()).parallelStream().forEachOrdered(qwe);
		list.forEach(System.out::println);
	}

Use thread-safe synchronizedList And added using for Eachordered to arrange the order Lambda's for Each is done in sequence, so sysout is the same

2019-11-08T17:40:22.228Z: 0
2019-11-08T17:40:22.259Z: 1
2019-11-08T17:40:22.259Z: 2
2019-11-08T17:40:22.260Z: 3
2019-11-08T17:40:22.260Z: 4
2019-11-08T17:40:22.260Z: 5
2019-11-08T17:40:22.260Z: 6
2019-11-08T17:40:22.260Z: 7
2019-11-08T17:40:22.260Z: 8

It will do it beautifully

In a word

If you change it at the same time, there will be a conflict! Stop! I mean Is it all right to switch to a thread-safe one if you are careful?

Recommended Posts

Thread-safe list
List method
Work list
Link list
Docker command list
Selenide option list
Java memorandum (list)
Clone Java List.
[Swift] Capture list
Array / list / map
[Docker] Command list
About List [Java]