ASingh
ASingh

Reputation: 485

Relation between Synchronized and Final in JAVA

I want to know the relation between synchronized and final in JAVA. I have read a few articles and everybody mentions should initialise a object in the constructor using final fields otherwise un-initialised objects may cause synchronization issues between multiple threads using the same object.

For. e.g. the below code:

class FinalFieldExample {
  final int x;
  int y;
  static FinalFieldExample f;
  public FinalFieldExample() {
    x = 3;
    y = 4;
  }

  static void writer() {
  f = new FinalFieldExample();
  }

  static void reader() {
    if (f != null) {
    int i = f.x;
    int j = f.y;
  }
 }  
}

The reader may read the value of x correctly but may read value of y as 0 since it is not declared final.

Why is this happening?

Upvotes: 1

Views: 139

Answers (2)

assylias
assylias

Reputation: 328785

This has to do with the final fields semantics. The JLS #17.5 gives a good summary:

The usage model for final fields is a simple one: Set the final fields for an object in that object's constructor; and do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields.

In other words, provided that you don't let this escape during construction, you have the guarantee that all threads will see the correct value for x (i.e. 3).

Regarding the other field (y), in the absence of synchronization, no guarantee is given as to which value will be seen (the default or the constructor value).

Upvotes: 2

OldCurmudgeon
OldCurmudgeon

Reputation: 65859

final fields have little to do with threading. I suspect you are thinking of volatile fields which do act a little like you describe.

Upvotes: -1

Related Questions