我应该同步构造函数吗?

Zhe*_*lov 2 java concurrency synchronized

考虑一个代表简单单元格的类:

class Cell {
    private int x;

    Cell(int x) {
        this.x = x;
    }

    int getX() {
        return x;
    }

    void setX(int x) {
        this.x = x;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要使其成为线程安全的,是否应该仅使方法同步或使构造函数同步?

class Cell {
    private int x;

    Cell(int x) {
        synchronized(this) { // <- Is this synchronization necessary?
            this.x = x;
        }
    }

    synchronized int getX() {
        return x;
    }

    synchronized void setX(int x) {
        this.x = x;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果是,为什么构造函数中没有synchronizedjava.util.Vector

Joh*_*int 5

按照JLS#8.8.3

实际上,没有必要使构造函数同步,因为它会锁定正在构造的对象,通常在对象的所有构造函数完成工作之前,其他线程无法使用该对象。

因此,这意味着引用在访问之前已同步。

由于正确同步,可以说在构造函数中发生的写操作将在对象发布之前进行,只要在该字段上保持一致即可

就您而言,由于getX()setX()都是同步的,因此同步是一致的,您不需要在构造函数中进行同步。


现在,您是否需要synchronize(this)构造函数? ,正如JLS所提到的那样,它在您不知道的情况下隐式同步。