简体   繁体   English

我是否需要在多个线程之间同步 getter 函数?

[英]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.

相关问题 如果我有多个要插入MySQL的线程,是否需要同步? - Do I need to synchronize if I have multiple threads that will insert to MySQL? 如果它们由不同的线程更新和读取,是否需要同步CopyOnWriteArrayList中的项目? - Do I need to synchronize items in a CopyOnWriteArrayList if they are updated and read by different threads? 我需要同步吗 - Do I need Synchronize this Java如何正确同步多个线程上的arraylist? - Java how do I properly synchronize an arraylist over multiple threads? 如何同步对多个线程访问的数组列表的访问? - How do I synchronize access to an array list accessed by multiple threads? 在 Java 中,如何在 TextArea 中使用多线程? 我需要同步我的线程吗? - In Java, how do I use multithreading in TextArea? Do I need to synchronize my threads? 我需要同步 writeObject() 吗? - Do I need to synchronize writeObject()? 在这种情况下是否需要同步 - Do I need to synchronize in this situation 即使两个线程不同时读写,我也需要同步吗? - Do I need to synchronize even if two threads don't read and write simultaneously? 我是否需要锁定数据库表或只是同步从不同线程调用时写入数据库的方法? - Do I need to lock the DB table or just synchronize the method that writes to the DB when called from different threads?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM