Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a list passed to a function be modofied by another thread in Java?

Integer getElement( List<Integer> list ) {

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

   return list.get( i );

}

The question: while this function has been called from a thread, IS there a way the list passed to this function can be modified by another thread?

like image 580
Mocha Avatar asked Sep 24 '11 10:09

Mocha


4 Answers

The list being passed into your function is a reference to a list object. If any other threads have references to the same list object, then this is not thread safe.

like image 145
driis Avatar answered Oct 06 '22 00:10

driis


No. java.util.List doesn't guarantee thread safety. The list can be changed between list.size() and list.get() by another thread. Moreover memory inconsistency is also a problem.

I could think three ways to solve it:

  1. Use immutable list. Collections.unmodifiableList(list) is fine, Guava's ImmuntableList is better.
  2. Synchronized the list. but you have to synchronize the list instance all over the program.
  3. List in java.util.concurrent. It's a sophisticated concurrency solution.
like image 44
卢声远 Shengyuan Lu Avatar answered Oct 06 '22 01:10

卢声远 Shengyuan Lu


> Integer getElement( List<Integer> list ) {
> 
>    int i = Random.getInt( list.size() );
> 
>    return list.get( i );
> 
> }

The question: while this function method has been called from a thread, IS there a way the list passed to this function can be modified by another thread?

(first Java doesn't have "functions", it has "methods")

It DEPENDS on the List implementation. Integer is immutable and if you're List implementation is immutable and correctly implemented, then the list cannot be modified and is completely threadsafe.

If you're List implementation is not immutable, then, yes, the list can be modified by another thread.

An example of an immutable List implementation would be, in the excellent Google Guava API, the ImmutableList which extends Java List and which is fully threadsafe. There are other examples of fully immutable List implementation and they are fully threadsafe (and of course are typically meant to be used with completely threadsafe objects, like the fully immutable Integer class).

like image 26
SyntaxT3rr0r Avatar answered Oct 06 '22 01:10

SyntaxT3rr0r


Is a list passed to a function thread safe in Java?

A list 'passed to a function' is the same as any other list. It is threadsafe if the list is already threadsafe, or if no other thread can see the list.

like image 25
user207421 Avatar answered Oct 06 '22 01:10

user207421