Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Non static field synchronization  RSS feed

 
James Winfrey
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
 
Pallav Bora
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!