Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronization basics

 
amol re
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class MyClass
{
public synchronized void methodA()
{
//do something
}

public synchronized void methodB()
{
//do something
}

public void methodC()
{
//do something
}
}
Threads T1 and T2 have the same instance of MyClass, lets say oMyClass.

T1 calls methodA. While methodA is executing in T1, T2 calls methodB.
What happens?? - T2 has to wait for T1 to release the lock so that it can obtain it and enter methodB. This is understood.
T1 calls methodA. While methodA is executing in T1, T2 calls methodC.
What happens?? - Even though methodC is not synchronized, T2 still has to wait because "if a instance method is synchronized and under execution, no other thread can call any instance method on that object. IS this right??
T1 calls methodC. While methodC is executing in T1, T2 calls methodA.
What happens?? - ?? I think T2 can access methodA without having to wait for anything. Is this right? This would mean that corruption is possible in this case if methodC and methodA are both manipulating any particular member variables.
Thanks in advance
amol
 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where did you see that quotation from your second example? The way I understand synchronization is that a non-synchronized method will never try to obtain the object's monitor. That means that thread 2 will be allowed to execute methodC() even while thread 1 is in the middle of methodA(). Still, I'm happy to be proven wrong.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greg, you're right.
- Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic