'Do variables/flags can be affected by another thread on a non-synchronized method?
For example I have a non-synchronized method like this:
public void nonSynchronized(){
boolean flag = false;
if(/*some condition*/){
flag = true;
}
//more line of codes here
if(flag == true){
//do something here - let's say line 33.
}
}
What if a first thread executes the method then sets the flag
to true
, and before executing the line 33 another thread executes the method then resets the variable flag
to false
, Will the first thread still execute line 33?
Solution 1:[1]
Your flag
is a local variable. Each thread gets its own copy on the stack. They don't interfere with each-other at all. That can only happen with shared state, i.e. things on the heap, i.e. fields of the object.
Solution 2:[2]
No. its(boolean flag) is a local variable. Local variable are not on shared memory. they are local/private to thread stack and hence not effected other threads/processor.
Solution 3:[3]
When you create a thread it will have its own stack. Each thread will have its own stack and one thread never shares its stack with other thread. All local variables defined in your program will be allocated memory in stack. Hence the answer is Yes your flag
variable will be thread safe.
Solution 4:[4]
Your method is thread safe as it is not working on any shared resource such as a static variable. Your flag is a method variable, and each thread will have a local copy of it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Thilo |
Solution 2 | veritas |
Solution 3 | AllTooSir |
Solution 4 | Juned Ahsan |