Javi Albors
Javi Albors

Reputation: 77

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(); }?

I'm sure it would be needed if it was a setter, as any other thread could be setting a new value.

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?

Upvotes: 1

Views: 93

Answers (2)

Gray
Gray

Reputation: 116908

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?

The devil is in the details here. Whether you can access the variable in multiple threads 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. That is the only guarantee that the Java memory model gives in terms of publishing classes.

If the field is final then it is guaranteed to be appropriately initialized and visible to other threads. 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 (or mark it as volatile) to gets its memory updated and to insure that the field has been appropriately initialized.

Upvotes: 2

queeg
queeg

Reputation: 9463

As you state the variable does not change you do not have to synchronize parallel read access.

Upvotes: 2

Related Questions