views:

774

answers:

3

What is final variable ? (if I write final int temp ; in function what is the meaning ?)
For which goal use final variable(both class variable and in function variable) ?
why variable in synchronized block must declare final ?

+10  A: 

Basically it just means you can't change the value. For instance variables, you have to assign any final variables once (and only once) in the constructor (or with a variable initializer). Synchronization is a pretty orthogonal concept.

The primary reason for making a local variable final is so you can use it in an anonymous inner class... this has nothing to do with being in a synchronized block.

Final variables are useful for immutable classes, admittedly - and immutability makes life easier in a multi-threaded environment - but that's the only relationship between the two that I can think of...

EDIT: Wildwezyr's comment makes sense in terms of not changing the variable on which you are synchronizing. That would be dangerous, for the reasons he's given. Is that what you meant by "variable in synchronized block"?

Jon Skeet
have you ever seen this warning: "Synchronization on non-final field"?
WildWezyr
@WildWezyr: I haven't, but I understand why it would occur.
Jon Skeet
+3  A: 

In addition to what Jon Skeet said, the value can't be changed but the contents may be changed.

final Integer one = new Integer(1);
...
one = new Integer(2); // compile error

final List list = new ArrayList();
...
list = new ArrayList(); // compile error
list.add(1); // Changes list, but that's fine!

Also be aware that final and static final are not the same. final is within the scope of the instance, whereas static final is the same for all instances of a class (in other languages this could be called a constant).

Personally I think the advantage of final, even when not absolutely required to get your software working, is in the semantical meaning. It offers you the possibility to say to the compiler and the next person working on that code that this variable is not meant to be changed, and that trying to change it could result in a bug.

extraneon
+6  A: 

Final variables and synchronized code blocks do have something in common... If you declare non-final variable a and then write synchronized (a) { System.out.println('xxx'); } you will get warning "Synchronization on non-final field" - at least in NetBeans.

Why you should not be synchronizing on non-final field? Because if field value may change, then different threads may be synchronizing on different objects (different values of the field) - so there could be no synchronization at all (every thread may enter synchronized block at the same time).

Look here for example of real-life trouble caused by synchronizing on non-final field: http://forums.sun.com/thread.jspa?threadID=5379204

WildWezyr