Is a method thread-safe if the return value is declared/returned outside of a synchronized block?
-
01-06-2021 - |
Question
public Foo getFoo(){
Foo foo = null;
synchronized(fooList){
if(fooList.size() > 0){
foo = fooList.remove(0);
}
}
return foo;
}
Since foo
is declared outside of the synchronized block, does the potential exist of returning bad data?
Solution
Each thread instance calling getFoo()
will have its own foo
instance. Thus foo
is thread safe and doesn't need synchronization.
OTHER TIPS
What does "bad data" mean in this context? fooList
may change asynchronously before synchronized(fooList)
and after the corresponding closing brace, before return foo;
(more generally speaking, up to the moment the returned value is used.) What is your ultimate goal?
getFoo
will not return stale data, since Foo foo
is local variable AND fooList
is synchronized
Local variable is thread safe since each thread call will create a new Foo
object, instead of sharing single object. While instead variable is not thread safe, since multiple threads can access fooList
, but in this case the fooList
is already synchronized.