Can I use end field synchronization?

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.

+5
source share
6 answers

Now I doubt the lock field, which is declared final, will it be?

Yes, the considered best practice is only to block field objects final.

, , , .

+9

. , - .

+1

, . , static.

+1

Java . final , REFERENCE , .

:

final Bar bar = new Bar(); //bar hase property lock
bar.lock = XYZ; //will work, object is not FINAL
bar = new Bar(); //fail, the reference is FINAL
0

, / . , .

, ; , .

, , . , , ..

0

All Articles