[英]Is a method thread-safe if the return value is declared/returned outside of a synchronized block?
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? 由于
foo
是在同步块外部声明的,因此是否存在返回错误数据的可能性?
Each thread instance calling getFoo()
will have its own foo
instance. 每个调用
getFoo()
线程实例将具有其自己的foo
实例。 Thus foo
is thread safe and doesn't need synchronization. 因此,
foo
是线程安全的,不需要同步。
What does "bad data" mean in this context? 在这种情况下,“不良数据”是什么意思?
fooList
may change asynchronously before synchronized(fooList)
and after the corresponding closing brace, before return foo;
fooList
可能在synchronized(fooList)
之前和相应的synchronized(fooList)
括号之后, return foo;
之前异步更改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 getFoo
不会返回过期数据,因为Foo foo
是局部变量, fooList
同步
Local variable is thread safe since each thread call will create a new Foo
object, instead of sharing single object. 局部变量是线程安全的,因为每个线程调用都会创建一个新的
Foo
对象,而不是共享单个对象。 While instead variable is not thread safe, since multiple threads can access fooList
, but in this case the fooList
is already synchronized. 相反,变量不是线程安全的,因为多个线程可以访问
fooList
,但是在这种情况下, fooList
已经同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.