Concurrent reads from read only fields and writes in read/write fields in a shared object

78 Views Asked by At

Lets say that I have this class:

public SharedObject {
  private int readOnlyField;
  private int readWriteField;

  public SharedObject(int field1, int field2) {
    this.readOnlyField = field1;
    this.readWriteField = field2;
  }

  public getField1() {...}

  public synchronized getField2() {...}

  public synchronized setField2(...) {...}
}

Can I have multiple threads that use these 3 methods concurrently?

Obviously I can with the last 2 synchronized methods, but I am not sure if getField1() can be executed concurrently with the other 2.

I think that the answer is yes, but just to be sure if I am missing some subtleties.

2

There are 2 best solutions below

3
On BEST ANSWER

For getField1 it can be executed simultaneously by 2 threads without any wait and synchronization. And since you are not having any setter, and its value is initialized upon object instantiation, so there are no change of dirty read as well.

For getField2 and setField2, no 2 threads and execute these methods at same time for the same instance of SharedObject.

Hope this helps!!!

0
On

Yes. Other thread(s) can execute a function which is not marked as synchronized.

So, in your case :

No two threads can execute getField2 and setField2 simultaneously. But getField1() can be executed simultaneously with either getField2 or setField2