Non-interference exact meaning in Java 8 streams

后端 未结 2 1049
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 16:56

Does the non-interference requirement for using streams of non-concurrent data structure sources mean that we can\'t change the state of an element of the data stru

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 17:21

    Modifying the state of an object stored in a data structure is different from reassigning an element of a data structure.

    When the other writes "changing the value of an element" presumably they mean as if assigning a new object to an index of an existing List.

    From your link:

    It is best to avoid any side-effects in the lambdas passed to stream methods. While some side-effects, such as debugging statements that print out values are usually safe, accessing mutable state from these lambdas can cause data races or surprising behavior since lambdas may be executed from many threads simultaneously, and may not see elements in their natural encounter order. Non-interference includes not only not interfering with the source, but not interfering with other lambdas; this sort of interference can arise when one lambda modifies mutable state and another lambda reads it.

    As long as the non-interference requirement is satisfied, we can execute parallel operations safely and with predictable results even on non-thread-safe sources such as ArrayList.

    This pertains specifically to parallelism and is no different than any other concurrent programming. Modifying state can cause issues with visibility amongst threads.

提交回复
热议问题