Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I use synchronized to a final field?

Consider following code, I want to make it a thread safe class, so that it will never get 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;
    }
  } 
}

I am now doubt of the lock field, which is declared to be final, will this matter? or it will break the thread safety?

I think if the lock field is not declared to be final, this should be a thread-safe class. If this conclusion is wrong, please correct me, thank you.

like image 233
alaska Avatar asked Jul 13 '12 20:07

alaska


1 Answers

I am now doubt of the lock field, which is declared to be final, will this matter?

Yes, its considered best practice to only lock final field objects.

If you can change the reference you can change which object is locked, breaking thread safety.

like image 160
Peter Lawrey Avatar answered Sep 24 '22 19:09

Peter Lawrey