aspose file tools
The moose likes Threads and Synchronization and the fly likes Class locks & non-static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Class locks & non-static methods" Watch "Class locks & non-static methods" New topic
Author

Class locks & non-static methods

Mark Venn
Greenhorn

Joined: Jun 08, 2008
Posts: 2
I understand that each object has its own lock and (non-static) synchronised code cannot be entered by a thread if another thread already has taken that particular object's lock.

I've just read (Head First Java P.522) that static methods can be synchronised and that in this case a class lock is taken.

My question is ; if thread A is running a synchronised static method and holds the class lock, can thread B running a synchronised non-static method on an otherwise unlocked object, still proceed? (or does it have to wait for the class lock to clear also?)

My thinking being, that the non-static method could be working with a static variable that the static method is also changing.

cheers
Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1220

Hi Mark,

welcome to the JavaRanch

Synchronization only works if you synchronize the methods in question with the same lock. So for your question, static synchronized methods don't compete with non-static synchronized methods because, as you already said, they're using different locks.

Of course you could synchronize static and non-static methods at the same time if you need to, but then the synchronized modifier won't help. You would have to use a synchronized block with a common lock instead of the intrinsic locks.

Marco
Mark Venn
Greenhorn

Joined: Jun 08, 2008
Posts: 2
Hi Marco,

understood - thanks for clarifying.

cheers
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Class locks & non-static methods
 
Similar Threads
objects and lock
threads synchronized methods
thread lock (monitor) question
difference between static synchronized method and non static synchronized method
SCJD