what does this mean?

public class Foo {
private static Map bar = new TreeMap();
...
public static void baz() {
synchronized (bar) {
// do something
}
}


This snippet of code will be marked by one of Intellij's inspections.
It says "Synchronization on a non-final field 'bar' is unlikely to have useful semantics"

What does that mean? I've looked in a few of my Java books and on google
but I can't find any info on why having 'bar' be final is better or more correct.

Thanks,
Kevin.

2 comments
Comment actions Permalink

If bar is ever assigned to, you could have a race condition causing multiple threads to execute in the synchronized section. That would be unlikely to be the desired behaviour, and the errors it caused could be incredibly difficult to diagnose. If bar is never assigned to, it should be final.

Note that this inspection, like many others, is not intended to highlight only issues which will definitely cause problems. It is intended to highlight coding practices that could cause problems, particular as your code evolves. Even if you never reassign bar, some later maintenance programmer might, because he didn't realize that it would induce subtle race conditions.

IIRC, this inspection was derived from a recommendation in Josh Bloch's Effective Java, if you want to learn more.

--Dave Griffith

0
Comment actions Permalink

Thanks for the explanation.

0

Please sign in to leave a comment.