This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
1) I hava a baseclass CLass A which has a instance String variable. Abstract class A { protected String var = "base"; abstract protected void modify(string input); } 2) I have a subclass Class B which extends Class A class B extends Class A { modify(String input){ if (input.equlasIgnorecase("A") var = "subclass"; else var ="SubClass1" }
}
My question is Class A is accessed by multiple threads so ineffect multiple threads are modifiying the the variable "Var" based on the input value. Do I need to synchronize on the "Var" variable to make sure right vaues are assigned? IF so can is below version the right way to do it? Please bear with me as I'm new to java . Also will it take any performance hit? class B extends Class A { modify(String input){ synchronized (var){ if (input.equlasIgnorecase("A") var = "subclass"; else var ="SubClass1" } }
Do I need to synchronize on the "Var" variable to make sure right vaues are assigned? IF so can is below version the right way to do it? Please bear with me as I'm new to java . Also will it take any performance hit?
Yes, you need to synchronized in order to protect shared data. And no, how you are doing it will *not* work.
Synchronizations is based on objects -- not references. Synchronizing with a reference variable that changes means that different threads will be synchronizing on different variables.
In your case, since you just need to protect an instance variable. Synchronizing on the "this" variable should work.