Consider a class that represents a simple cell:
class Cell {
private int x;
Cell(int x) {
this.x = x;
}
int getX() {
return x;
}
void setX(int x) {
this.x = x;
}
}
If I want to make it thread-safe, should I only make the methods synchronized or the constructor too?
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;
}
}
If yes, why are there no synchronized
blocks in java.util.Vector
constructors?