• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronizing on a static member object

 
Timothy Sam
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys!

I already passed SCJP. But the learning doesn't stop there right? And it might be beneficial to our friends here so I decided to post it here.

I think I read somewhere that class variables(static) have their own lock? What does that mean? If I'm programming in a multu-threaded environment, why do I still need to synchronize on a static member Object? Thanks!
 
Henry Wong
author
Marshal
Pie
Posts: 21423
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I read somewhere that class variables(static) have their own lock? What does that mean? If I'm programming in a multu-threaded environment, why do I still need to synchronize on a static member Object?


All objects have a lock, it doesn't matter if the object is referred to from a local variable, instance variable, or static variable. On the other hand, variables are just references, they don't have any locks directly associated with them.

You *need* to synchronize on an object -- whether static or not -- based on the need of the application. If the thread safety is dependent on static access to a variable, then you need a lock at the same scope -- either use that variable or an object at the same scope of that variable.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic