[英]Do I need to synchronize a getter function between multiple threads?
So if I have multiple threads wanting to access a variable in the same object, using a getter, do I need to synchronize (var) { var.get(); }
因此,如果我有多个线程想要使用 getter 访问同一个对象中的变量,我是否需要
synchronize (var) { var.get(); }
synchronize (var) { var.get(); }
? synchronize (var) { var.get(); }
?
I'm sure it would be needed if it was a setter, as any other thread could be setting a new value.我敢肯定,如果它是一个 setter,那将是必需的,因为任何其他线程都可以设置一个新值。
But in this case, this variable is only read by the threads and does not change.但是在这种情况下,这个变量只被线程读取并且不会改变。
Though, multiple threads could be checking its value at the same time.但是,多个线程可以同时检查它的值。
Do I need to synchronize the getter?我需要同步 getter 吗?
As you state the variable does not change you do not have to synchronize parallel read access.当您声明变量不会更改时,您不必同步并行读取访问。
But in this case, this variable is only read by the threads and does not change.
但是在这种情况下,这个变量只被线程读取并且不会改变。
The devil is in the details here.细节决定成败。 This depends on whether or not the field is
final
and whether the object was created before the threads were by the same thread that started the threads.这取决于字段是否为
final
字段以及对象是否在线程由启动线程的同一线程创建之前创建。 That is the only guarantee that the Java memory model gives in terms of publishing classes.这是 Java 内存模型在发布类方面提供的唯一保证。
If the field is final
then it is guaranteed to be appropriately initialized and visible to other threads.如果该字段是
final
的,则可以保证它被适当地初始化并且对其他线程可见。 If it is not final, regardless if the threads just read the field, if the object was created after the threads were running, you will need to synchronize on it to gets its memory updated and to insure that the field has been appropriately initialized.如果它不是最终的,不管线程是否刚刚读取该字段,如果该对象是在线程运行之后创建的,您将需要对其进行同步以更新其内存并确保该字段已被适当初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.