Consider the following code, I want to make it a thread safe class so that it never gets an odd number:
class Test {
private int value = 0;
private final Object lock;
public void add() {
synchronized (lock) {
value++;
value++;
}
}
public int getValue() {
synchronized (lock) {
return value;
}
}
}
Now I doubt the blocking area, which is declared final, will it be? or will it violate thread safety?
I think that if the lock field is not declared final, this should be a thread-safe class. If this conclusion is incorrect, please correct me, thanks.
source
share