Final variable and synchronized block in java

What is a final variable? (if I write final int temp ; in a function, what's the point?)
For what purpose do I use a finite variable (both a class variable and a function variable)?
why should the variable in the synchronized block declare the final?

+6
java variables synchronized final
source share
3 answers

This basically means that you cannot change the value. For example, variables, you must assign any final variables once (and only once) in the constructor (or with the variable initializer). Synchronization is a pretty orthogonal concept.

The main reason for creating a local variable value is that you can use it in an anonymous inner class ... it has nothing to do with being in a synchronized block.

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

EDIT: The Wildwezyr comment makes sense in terms of not changing the variable on which you are synchronizing. This would be dangerous for the reasons he gave. Is that what you mean by “variable in synchronized block”?

+14
source share

The final variables and synchronized blocks of code have something in common ... If you declare a non-final variable a , then write synchronized (a) { System.out.println('xxx'); } synchronized (a) { System.out.println('xxx'); } , you will receive a warning “Synchronization in a non-final field” - at least in NetBeans.

Why you should not be synchronized in a non-final field? Since, if the field value can change, different streams can be synchronized on different objects (different field values), therefore, there can be no synchronization at all (each stream can simultaneously enter a synchronized block).

Look here, for example, at a problem with a real life situation caused by synchronization in a non-final field: http://forums.sun.com/thread.jspa?threadID=5379204

+13
source share

In addition to what John Skeet said, the value cannot be changed, but the contents can 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 fine! 

Also keep in mind that the final and static finals do not match. final is within the instance instance, while the static ending is the same for all instances of the class (in other languages ​​this can be called a constant).

Personally, I believe that the advantage of the final, even when not absolutely necessary in order to make your software work, is in semantic meaning. It offers you the opportunity to tell the compiler and the next person working on this code that this variable is not intended to be modified, and that attempting to change it may lead to an error.

+4
source share

All Articles