Is the list passed to the function stream in Java?
Question: while this function was called from a thread, is there a way that the list passed to this function can be changed by another thread?
This concerns thread safety, and in particular the list instance. It depends on the specific class of the list instance (this is both simultaneous behavior and mutability behavior). If this instance is mutable, it matters to the visibility / exposure of this list.
I changed your example in the hope of better understanding the issue and providing more specific solutions:
private void method1 { final List<Integer> list = new ArrayList<Integer>(); list.add(Integer.valueOf(1));
Two ways:
- parallel instances
- <i> are unchanging
concurrent
list instances:
- java.util.concurrent.CopyOnWriteArrayList
- java.util.Collections.synchronizedList ()
Based on the above code, here are a few options on how to make threadElement thread safe.
immutable
Best : make immutable
list (so no sync needed)
final List<Integer> list1 = Arrays.asList(1);
Con: causes a new problem with the mutator. To solve this problem, an understanding of the whole problem will be required.
concurrent
1) Defensive copy in getElement () combined with concurrent
instance.
private Integer getElement(Collection<Integer> list) { final List<Integer> copy; synchronized (list) {
Con: performance for copying
2) Rewrite getElement () so that it uses only iterator with concurrent
instance
Con: current implementation does not provide uniform distribution
There is no easy way to solve concurrency.