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.
The moose likes Threads and Synchronization and the fly likes Synchronization question- please help Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Synchronization question- please help" Watch "Synchronization question- please help" New topic
Author

Synchronization question- please help

Sanju Shah
Greenhorn

Joined: Apr 06, 2006
Posts: 19
Hi all,

Following is what I'm trying to do.

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"
}
}

}

THanks
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16695
    
  19

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.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Synchronization question- please help
 
Similar Threads
overriding a concrete method by abstract method
from a mock exam
ClassCastException
null passed as parameter
Synchronizing a instance variable - please help