Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ENLIGHTENING, thread synchronization, concept clarification --plz help

 
sarim raza
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a thread say A, acquires the lock of an object, and this object's class has two synchronized methods and two non synchronized methods ...
Q1] Can Thread A only execute one of the synchronized methods of this object at one time ?
Q2] I know that no other thread can execute any synchronized method of the object during this time (when thread A has a lock on the object, and is implementing a synchronized method) ....
BUT
CAN OTHER THREADS EXECUTE THE NON-SYNCHRONIZED METHODS OF THIS OBJECT DURING THIS TIME, simulatenously ???
thanks
 
Cherry Mathew
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The theory of synchronization will help clear u r doubt.
When a thread enters synchronized method or block it tries to acquire the lock of that object.If it doesnt have the lock it waits for it. But for a non-synchronized function it wont ask for the lock and it will execute it even though the lock is with another thread.
hope this clear u r doubt
 
George Toronto
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, sarim
Let us suppose the segment of code seems like the following:


[B]Q1] Can Thread A only execute one of the synchronized methods of this object at one time ?

That is right. Every object of a class has only one lock with a key. When a thread is excuting a sychronized method of a object, that is , the thread owns the only lock, and the other threads have to wait when they want to access the sychronized method or other sychronized methods of the object. But, the thread which is excuting a sychronized method can also access other sychronized methods without being blocked.
CAN OTHER THREADS EXECUTE THE NON-SYNCHRONIZED METHODS OF THIS OBJECT DURING THIS TIME, simulatenously ???

Of course, the thread running can access the non-sychronized methods. the non-syschronized methods can be invoked and called by any thread at any time.
You can try several examples from Khalid Book or RHE Book. By doing that, you can understand thread deep and clearly.
regds
George
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic