Synchronizing methods in java
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Shoban_kumar
Posted On:   Thursday, May 15, 2003 03:18 AM

Hi

If i have a class with two methods say, method1() and method2() and both are synchronized.

If a thread1 calls the first method(method1) which is synchronized, can i able to call the second method(method2) of the same class which is also synchronized using another thread say thread2.


Say,If i can call the second method, then what would be the case if both the methods are accessing a common global variable.


Kindly answer my question.

Re: Synchronizing methods in java

Posted By:   Anonymous  
Posted On:   Friday, May 16, 2003 01:00 AM

If both methods are non static, like:



public synchronized void method1 ( ){

//...

}


public synchronized void method2 ( ){

//...

}



then this means they are both synchronizing on the object, so only one thread at a time can hold the lock of the object instance.
If one thread enters method1, other threads can't enter method1 or method2, because both are 'guarded' by synchronization on the object instance.



If both are static, this works the same, except that the synchronization is done on the class level:



public static synchronized void method1 ( ){

//...

}

public static synchronized void method2 ( ){

//...

}



If however, one method is static and one method is not, like this:


public synchronized void method1 ( ){

//...

}

public static synchronized void method2 ( ){

//...

}



The access to method1 is synchrnonized on the object level, and the access to method2 on the class level. This means that if one thread enters method1, the other cannot enter method1, and must wait, but it can enter method2, because the synchronization is done on another object (the class object and not the object instance).



Hope this helps.


regards,

Gunther.

www.javacoding.net
About | Sitemap | Contact