Can the list passed to the function be modified by another thread in Java?

Integer getElement( List<Integer> list ) {
Integer getElement( List<Integer> list ) {

   int i = Random.getInt( list.size() );

   return list.get( i );

}

Question: Although this function is called from one thread, is there a method to modify the list passed to this function by another thread?

Solution

java. util. List does not guarantee thread safety The list can be in list Size () and list Get () is changed by another thread In addition, memory inconsistency is also a problem

I can think of three solutions:

>Use immutable list Collections. Unmodifiablelist is good, and guava's immuntablelist is better. > Synchronized list But you must synchronize list instances throughout the program. > In Java util. Listed in concurrent This is a complex concurrency solution

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>