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?
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.
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:
> Integer getElement( List<Integer> list ) {
>
> int i = Random.getInt( list.size() );
>
> return list.get( i );
>
> }
The question: while this
functionmethod 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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With