Java 8 non-threading requirement

I am new to Java 8.

Non-intervention is important to ensure consistent Java flow behavior. Imagine that we process a large flow of data and during the process the source changes. The result will be unpredictable. This is independent of the flow processing mode, parallel or sequential.

The source can be changed until the operator terminal operation is called. In addition, the source should not be changed until the thread completes. Therefore, processing parallel modifications in the source stream is critical to ensure consistent stream performance.

The above quotes are taken from here .

Could someone make some simple example that would shed light on why the mutation of the flow source will give such big problems?

+4
source share
1 answer

Well, the oracle example here is self explanatory. The first one is:

List<String> l = new ArrayList<>(Arrays.asList("one", "two"));
 Stream<String> sl = l.stream();
 l.add("three");
 String s = l.collect(Collectors.joining(" "));

If you change lby adding a few more elements to it before calling the terminal ( Collectors.joining) operation , you are fine; but note that it Streamconsists of three elements, not two; at the time you created Stream through l.stream().

On the other hand:

  List<String> list = new ArrayList<>();
  list.add("test");
  list.forEach(x -> list.add(x));

will be thrown out ConcurrentModificationException, since you cannot change the source.

, , :

ConcurrentHashMap<String, Integer> cMap = new ConcurrentHashMap<>();
cMap.put("one", 1);
cMap.forEach((key, value) -> cMap.put(key + key, value + value));
System.out.println(cMap);

? , :

 {oneoneoneoneoneoneoneone=8, one=1, oneone=2, oneoneoneone=4}

zx (cMap.put("zx", 1)), :

{zxzx=2, zx=1}

.

+6

Source: https://habr.com/ru/post/1678330/


All Articles