Reputation: 19
Suppose I have the next class:
class Point {
int x, y, z;
public Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public **synchronized** int getSum() {
return x + y + z;
}
}
Is it possible to have a partially initialized fields in the synchronized getSum() method?
Upvotes: 0
Views: 107
Reputation: 20436
No. You need to make your fields final to guarantee that class is fully initialized before sharing with other thread.
Alternatively you can put invoking of constructor inside synchronized block. Share it outside said block.
Upvotes: 0
Reputation: 49
Synchronized provides both atomicity and visibility so sum should always be consistent.
Upvotes: -1