Win a copy of Kotlin for Android App Development this week in the Kotlin forum!
  • 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:
  • Campbell Ritchie
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

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.
 
pie. tiny ad:
Programmatically Create PDF Using Free Spire.PDF with Java
https://coderanch.com/wiki/703735/Programmatically-Create-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!