This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin 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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!