Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

objects and lock

 
jasmine alba
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does each object in java have a corresponding lock?
 
Chang Tzu-yu
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by jasmine alba:
Why does each object in java have a corresponding lock?


Sorry, I don't understand your question.

Please be more specific. Thanks.
 
Ravinder Partap
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every object in Java has a corresponding lock and that lock is used in multithreading enviornment to ensure the desirable access to the methods or the block of code.
When there are more than one thread working on the non-static methods (or the block of code in those methods.) than the lock taken on the object (the instance of some class) is taken by the thread and no other thread with the same instance of object can access those methods if they are synchronized. That means by synchronizing the method, you will ensure that any threads trying to run that method using the same instance will be prevented from simultaneous access.
But thread working with a different instance will not be affected, because it's acquiring a lock on the other instance.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic