• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Synchronization question- please help

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic