File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes synchronization basics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "synchronization basics" Watch "synchronization basics" New topic

synchronization basics

amol re
Ranch Hand

Joined: Mar 21, 2002
Posts: 36
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
Greg Charles

Joined: Oct 01, 2001
Posts: 2968

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
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Greg, you're right.
- Peter
I agree. Here's the link:
subject: synchronization basics
It's not a secret anymore!