How can I declare an object's member field as volatile? - java

If I have a variable of type SomeClass and one of its public members, say public int counter will be accessed by multiple threads, how can I declare volatility on that member field if I'm unable to modify SomeClass? Ideally, I'm guessing that counter would be declared volatile, but I'm unable to do that.

What you are trying to achieve is incompatible with separate compiling, and is therefore not possible. The volatile qualifier directs the compiler to treat a variable differently on each access, so every access to that variable from the module to the source of which you have no access would need to change as well. Since that module is compiled already, changing the way it treats some of its variables is not possible.

Related

Why is the Final modifier used in anonymous blocks when referencing a local variable from the main class [duplicate]

This question already has answers here:
Why are only final variables accessible in anonymous class?
(15 answers)
Cannot refer to a non-final variable inside an inner class defined in a different method
(20 answers)
Closed 7 years ago.
final JTextField jtfContent = new JTextField();
btnOK.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event){
jtfContent.setText("I am OK");
}
} );
If I omit final, I see the error "Cannot refer to a non-final variable jtfContent inside an inner class defined in a different method".
Why must an anonymous inner class require the outer classes instance variable to be final in order to access it?
Well first, let's all relax, and please put that gun down.
OK. Now the reason the language insists on that is that it cheats in order to provide your inner class functions access to the local variables they crave. The runtime makes a copy of the local execution context (and etc. as appropriate), and thus it insists that you make everything final so it can keep things honest.
If it didn't do that, then code that changed the value of a local variable after your object was constructed but before the inner class function runs might be confusing and weird.
This is the essence of a lot of the brouhaha around Java and "closures".
Note: the opening paragraph was a joke in reference to some all-caps text in the original composition of the OP.
The methods in an anonymous class
don't really have access to local
variables and method parameters.
Rather, when an object of the
anonymous class is instantiated,
copies of the final local
variables and method parameters
referred to by the object's methods
are stored as instance variables in
the object. The methods in the object
of the anonymous class really access
those hidden instance variables. [1]
Thus, the local variables and method parameters accessed by the methods of the local class must be declared final to prevent their values from changing after the object is instantiated.
[1] http://www.developer.com/java/other/article.php/3300881/The-Essence-of-OOP-using-Java-Anonymous-Classes.htm
The variables around the definition of the class live on the stack, so they are probably gone when the code inside the inner class runs (if you want to know why, search stack and heap). That's why inner classes don't actually use the variables in the containing method, but are constructed with copies of them.
This means that if you change the variable in the containing method after constructing the inner class, its value won't change in the inner class, even though you'd expect it to. To prevent confusion there, Java requires them to be final, so you expect not to be able to modify them.
The reason is that Java do not fully support so-called "Closures" - in which case the final would not be necessary - but instead have found a trick by letting the compiler generate some hidden variables which is used to give the functionality you see.
If you disassemble the generated byte code you can see how the compiler does it, including the strangely named hidden variables containing copies of the final variables.
It is an elegant solution to give functionality without bending the language backwards to do so.
Edit: For Java 8 lambdas give a more concise way to do what was previously done with anonymous classes. The restrictions on variables have also loosened from "final" to "essentially final" - you do not have to declare it final, but if it is treated like it is final (you could add the final keyword and your code would still compile) it can be used. This is a really nice change.
Since Java 8 final modifier is optional for outer instance variables. Value should be 'effectively final'. See answer Difference between final and effectively final.

Are class variables in Java shared between threads or not?

I was wondering when declaring a class variable (i.e. a variable declared outside a method) would potentially cause problems in a program that's executed by several threads. I suppose finals are save to use (i.e. not shared), and static variables are definitely shared between threads. But what about "standard" variables? When are they shared and when are they "private" to each individual thread?
Update: While I accept that local variables (within methods) are not shared and class variables usually are I would love to understand why that is (from a technical point of view). So any explanation to that effect (or links to articles that are fairly easy to understand) would be much appreciated.
Java provides the ThreadLocal<T> class to declare variables that are not shared between threads. Non-final parameters and local variables are also not shared between threads. final parameters and locals variables may be shared between threads when they are used in an anonymous class definition, but this shouldn't be a problem since they are final. In all other cases I can think of, variables can be shared between threads.
The short answer is, any method or variable, both static and non-static, has the potential to be accessed by more than one Thread if its access modifier makes it visible to that Thread.
The concept of "thread-safe" is entirely different. If a variable is read-only (final can be used to make primitives read-only, but only makes references to objects immutable, not the objects themselves), multi-threaded access of that variable is inherently thread-safe. If it can be written to, the proper use of synchronized blocks or the volatile keyword is necessary to ensure mutual exclusion.
There's nothing special about a standard variable that shields it from multi-threaded access and resulting problems. That's up to YOU the programmer to worry about.
If two threads need to safely access the same instance fields, then YOU have to write code to manage that.
Some common techniques are to use synchronized blocks to manage mutability, using atomic or final primitives (a final Object is not necessarily safe unless you know the Object isn't mutable), or simply use a ThreadLocal to give each thread its own unshared instance of the class.
Final doesn't mean 'not shared' just that the field cannot be overwritten, it can only be initialized one.
Static behavior is also not related to threading, static means that the field has a Class scope and not instance scope, meaning it's shared by all the instances of a Class.
If you want to protect a field from being modified by many threads, you have to manipulate it through synchronized methods.
Such variables are called the fields of the class, and they are definitely not "thread-safe" in general, even when they are final (because final only refers to the reference itself, not what's inside the object).

Local variables or member variables in Java

I have a question about local and member variables in Java. The situation is: Sometimes if I define a local variable, that variable has to be passed around into several levels of method calls. I often think, why should I just define a member variable for the class so that the variable is available everywhere in the class. A member variable of a class is like a global variable accessible everywhere in the class.
What's the best practice for this scenario? OR what's the right thing to do?
If I define it as a member variable, should it be a static or non-static variable?
Member variables hold characteristics -- attributes is another term -- for the 'thing' in your program represented by the class. If your variable holds something like that, make it a member variable; if it doesn't, don't.
Static variables hold characteristics of the class itself, as opposed to characteristics of objects of that class.
Don't make the decision based on whether you "pass ... into several levels of method calls.
Thinking about your general question, I came up with these guidelines from my experience:
Use the smallest poosible scope. If a local variable is fine, then why use a member variable?
Model the class according to the domain. If you have a value and it is part of the class responsibility, then modeling it as a class member seems to be appropiate.
To your second question: I do generally define static variables as final which make them constants. Non-final static members in a multi-threaded environment may easily introduce race conditions. It is easier to make access to non-static member thread-safe if needed.
It's behavioral. If your variable is part of your class attribute i.e. characterizes the class behavior then define it as the class member variable otherwise define a local variable inside the method.
In my opinion, passing the argument doesn't contribute in the attribute type definition.
It depends.
If you want all (or several), of your methods to access the same member variable, then declare it in the class.
Static or not depends on wether that information belongs to the Class (static), or to an instance of the class (non-static).
1.) If you are going to use it in multiple methods and need to pass it around make its member variable. If it is just for that method make it local.
2.) static means their is only one instance of that variable that is shared among everything. So for example I have a totalGameScore variable that will keep my score for the whole game no matter what. You'd want to make that variable static. Other than that lets say I have a health variable for my enemy. Each enemy will have its own health so I would NOT make that variable static.
You can also declare member variables private so that other classes cannot access them.
Constants should normally always be member variables.
If you decide to declare a member variable then you should consider the variables scope. If you are just reducing the number of parameters on internal method calls I would consider declaring the variable as private.
You should be careful of using Static because every instance of the class will use the same copy of the variable.

Why Java inner classes require "final" outer instance variables? [duplicate]

This question already has answers here:
Why are only final variables accessible in anonymous class?
(15 answers)
Cannot refer to a non-final variable inside an inner class defined in a different method
(20 answers)
Closed 7 years ago.
final JTextField jtfContent = new JTextField();
btnOK.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent event){
jtfContent.setText("I am OK");
}
} );
If I omit final, I see the error "Cannot refer to a non-final variable jtfContent inside an inner class defined in a different method".
Why must an anonymous inner class require the outer classes instance variable to be final in order to access it?
Well first, let's all relax, and please put that gun down.
OK. Now the reason the language insists on that is that it cheats in order to provide your inner class functions access to the local variables they crave. The runtime makes a copy of the local execution context (and etc. as appropriate), and thus it insists that you make everything final so it can keep things honest.
If it didn't do that, then code that changed the value of a local variable after your object was constructed but before the inner class function runs might be confusing and weird.
This is the essence of a lot of the brouhaha around Java and "closures".
Note: the opening paragraph was a joke in reference to some all-caps text in the original composition of the OP.
The methods in an anonymous class
don't really have access to local
variables and method parameters.
Rather, when an object of the
anonymous class is instantiated,
copies of the final local
variables and method parameters
referred to by the object's methods
are stored as instance variables in
the object. The methods in the object
of the anonymous class really access
those hidden instance variables. [1]
Thus, the local variables and method parameters accessed by the methods of the local class must be declared final to prevent their values from changing after the object is instantiated.
[1] http://www.developer.com/java/other/article.php/3300881/The-Essence-of-OOP-using-Java-Anonymous-Classes.htm
The variables around the definition of the class live on the stack, so they are probably gone when the code inside the inner class runs (if you want to know why, search stack and heap). That's why inner classes don't actually use the variables in the containing method, but are constructed with copies of them.
This means that if you change the variable in the containing method after constructing the inner class, its value won't change in the inner class, even though you'd expect it to. To prevent confusion there, Java requires them to be final, so you expect not to be able to modify them.
The reason is that Java do not fully support so-called "Closures" - in which case the final would not be necessary - but instead have found a trick by letting the compiler generate some hidden variables which is used to give the functionality you see.
If you disassemble the generated byte code you can see how the compiler does it, including the strangely named hidden variables containing copies of the final variables.
It is an elegant solution to give functionality without bending the language backwards to do so.
Edit: For Java 8 lambdas give a more concise way to do what was previously done with anonymous classes. The restrictions on variables have also loosened from "final" to "essentially final" - you do not have to declare it final, but if it is treated like it is final (you could add the final keyword and your code would still compile) it can be used. This is a really nice change.
Since Java 8 final modifier is optional for outer instance variables. Value should be 'effectively final'. See answer Difference between final and effectively final.

What is the difference between local and instance variables in Java?

Except the scope and the storage differences, are there any other major difference between instance and local variables in Java?
The main differences that I see are in their:
Scope: Local variables are visible only in the method or block they are declared whereas instance variables can been seen by all methods in the class.
Place where they are declared: Local variables are declared inside a method or a block whereas instance variables inside a class, but outside a method.
Existence time: Local variables are created when a method is called and destroyed when the method exits whereas instance variables are created using new and destroyed by the garbage collector when there aren't any reference to them.
Access: You can't access local variables, whereas instance variables can be accessed if they are declared as public.
Where they are declared: Local variables are declared in a method or a block before they are called, whereas instance variables can be declared anywhere in the class level (even after their use).
Instance variables always have value, even if they are not assigned by the code (then they will have for example null, 0, 0.0, and false). For local variables, there must be an assigned value by the code. Otherwise the compiler generates an error.
One extra thing I can think of:
Instance variables are given default values, i.e., null if it's an object reference, and 0 if it's an int.
Local variables don't get default values, and therefore need to be explicitly initialized (and the compiler usually complains if you fail to do this).
One other difference is you don't have to worry about concurrent access to local variables; whereas you do with instance variables in a multi-threaded environment.
No, you pretty much covered it. An instance variable belongs to an instance of a class, and a local variable belongs to a stack frame.
Instance variables are initialized to default values, but it's generally good practice to use explicit initializations anyway.
A local variable:
is declared inside a method/constructor or within a block (enclosed in braces)
must be initialized before use. Otherwise it won't compile.
An instance variable:
is declared inside a class.
initialization is not compulsory: if omitted, it contains the default value (0, 0.0, false, null, etc.)
-> local variable is declared in the body of a method and can be used
only from the point at which it’s declared through the end of the method
declaration.
-> An instance variable is declared in a class, but not in the body
of any of the class’s methods. Also, instance variables are accessible to all
methods of the class.
Aside from all that is already mentioned here, I would like to point out that local variables are a bit faster to access for the JVM. The JVM has got more work to do to read or write an instance variable compared to a a local variable.
This is still true for the current HotSpot server JVM, because it's not a VM optimization problem. It's rather caused by the fact that an instance variable is visible outside of the method and could thus be accessed from other threads while the method is executed.
Aside from all the differences mentioned in previous answers, I would like to point out one more difference that, instance variables can have access modifiers (like private, public, protected, etc.), but local variables will not have any access modifiers.
Local variables are on the stack, but member variables (instance variables) are on the heap.
Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.
Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.
Local variables are declared within a method.
Instance variables are declared inside a class but not within a method.
Local variables do not get a default value. The compiler complains if you try to use a local variable before before the variable is initialised.
However, instance variables always get a default value. If you don't explicitly assign a value to an instance variable, the instance variable still has a value.
integers 0
floating points 0
Boolean false
references null
The main difference is instance variables get default values. Like an int value gets zero and a char gets a null, but not the local variables.
You can leave uninitialized instance variable, but where as local variables must be initialized otherwise you will get compiler error.
Existence time:
I would like to tell you the major important difference between these variables is that when I encountered a problem where my instance variable during my software development worker life. Problem was occurring when user log in I have to return a username of user, who log in, but there is a problem, where for example one user log in it work successful but when another user log in while program run it return again a username, which log in before. I did run the program like debug mode and I could see a problem within my instance variable, which it could be local variable in my authentication method. The reason I tell that be careful when you work local and instance variable in programming language. All programmers don't take enough time simply topics, but small problems create great complexity.

Categories

Resources