File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronizing on a static member object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronizing on a static member object" Watch "Synchronizing on a static member object" New topic
Author

Synchronizing on a static member object

Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 746
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!


SCJP 1.5
http://devpinoy.org/blogs/lamia/ - http://everypesocounts.com/
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19070
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronizing on a static member object