0

I'm reading J.Bloch's effetive Java and now I'm at the section about documenting thread-safety. He provides an example using locks:

private final Object lock = new Object();

public void foo(){
    synchronized(lock){
        ...
    }
}

and said this:

Note that the lock field is declared final. This prevents you from inadvertently changing its contents, which could result in catastrophic unsynchronized access to the containing object.

Should we adhere to the rule always declaring lock object final? From the first glance, I could see that if the one thread modify the lock within the synchronized block and some other try to acquire the monitor of the modified object (which is free) right after the modifying. But it appears to me as a "theoretical problem" hardly reproducing in practice. Maybe I miss something?

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 1
    It could be considered 'defensive programming,' see https://en.wikipedia.org/wiki/Defensive_programming – Riley Carney Nov 17 '15 at 06:20
  • I disagree with the duplicate because what we're talking about here is a question of _style_. Are you going to delete your source code as soon as you get the program working? No? Then you must be saving it for someone to read (and maybe improve) later on. Source code is for _humans_, and the more obvious you make it, the easier it is to read. Declaring `lock` to be `final` makes it obvious that nothing tricky is going on. It's a _design pattern_ that everybody recognizes and understands. Without `final` a _wise_ programmer will have to take extra time to understand _why_ it's not final. – Solomon Slow Nov 17 '15 at 13:52

0 Answers0