Sincerely
Sincerely

Reputation: 19

Does the synchronized getter method see the fully or partially initialized object?

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

Answers (2)

talex
talex

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

Sandeep Gaur
Sandeep Gaur

Reputation: 49

Synchronized provides both atomicity and visibility so sum should always be consistent.

Upvotes: -1

Related Questions