Hien Nguyen
Hien Nguyen

Reputation: 764

Are code statements that are outside the synchronized statement thread-safe?

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
    doA();
    doB();
}

Following the java document's example above, the "nameList.add(name);doA();doB();" are thread-safe ?

Upvotes: 0

Views: 37

Answers (1)

EnabrenTane
EnabrenTane

Reputation: 7466

No. Only:

synchronized(this) { lastName = name; nameCount++; } Is shown to be threadsafe here.

doA() and doB() could have additional locking though, but may be called multiple times which could have unintended side effects.

Upvotes: 3

Related Questions