• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Non static field synchronization  RSS feed

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys

Why is it that access to non-static fields should be from synchronized non-static methods for thread safety? Assume Thread Safety is required.

Thanks
 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let me explain your questions with examples.
#1 Define a class
Class X
{
int val = 0;

// getValStatic is not correct. it is shown for explanation only
public static int getValStatic()
{
return val;
}
public static int getValInstance()
{
return val;
}
}
#2 instantiate 2 objects

X x1 = new X();
x1.val = 2;

X x2 = new X();
x2.val=3;

#3 Suppose static method could access instance variables. In that case if you call X.getValStatic(), it will not be clear which object's val is needed, x1 or x2. This is the reason static method is not allowed to access non static methods/variables.

# 4 As for Synchronization I guess the answer is just alowing one thread to access the method/variable ata time.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!