Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization question- please help  RSS feed

 
Sanju Shah
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!