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

semantic of synchronization

 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by adeel ansari:
how about this?

- when a thread is executing a synchronized block no other thread (using the same instance) can enter that block before it comes out.

- or the other thread (using the same instance) can enter the block but can not access that particular object, which we specified in synchronized(obj), simultaneously. and wait for the turn.

which one is right??
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first is right. On entering the synchronized block, the thread is getting the monitor on the object you are synchronizing on. The monitor is released when leaving the synchronized block (or when calling wait()); Only one thread can hold the monitor to an object at the same time.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by adeel ansari:
when a thread is executing a synchronized block no other thread (using the same instance) can enter that block before it comes out.

One important key to understanding synchronization is to realize that whether using a synchronized method or block you are always synchronizing on an object instance* -- not a method or block of code. The method or block only gives you the scope of the lock.

If you have two different synchronized blocks that use the same object instance for their lock, they will block each other. If all of class A's methods are synchronized, calling a method of an instance of A will block any other synchronized blocks using that same instance of A. Again, the locked instance is what matters.

* This is the same even for static synchronized methods. How? The methods lock the singleton Class instance.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the first is correct.
the second is absolutely and completely false.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i just remove this "(using the same instance)" from the first statement then what you people say.
 
Daniel Mayer
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by adeel ansari:
if i just remove this "(using the same instance)" from the first statement then what you people say.


Then it becomes wrong.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic