• Post Reply Bookmark Topic Watch Topic
  • New Topic

Class locks & non-static methods

 
Mark Venn
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marco,

understood - thanks for clarifying.

cheers
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!