• Post Reply Bookmark Topic Watch Topic
  • New Topic

Syncronization  RSS feed

 
mahesh bhat
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
If a synchronized method calls another method is that method too by default synchronized? Also can a synchronized method call another method which too is synchronized?
eg :
public class C {
public synchronized void m1() {

m2();
}
public void m2() {
....
....
...
}
}
In the above method would the call to m2 in m1 be syncronized ?
regards
mahesh
 
Andy Ceponis
Ranch Hand
Posts: 782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My understanding is that yes synchronized methods can call other methods. Those methods are not synchronized by default. And yes the method can call another synchronized method.
 
aiooua
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Obviously it would! . Isn't that just why we use the synchronized keyword.
Java uses the concept of monitor to achieve syncrhonization. Every time a thread calls a method that is synchronized, it locks the object which the method belongs to. Since the whole object is blocked all methods and properties that belong to it would be in mutual exclusion.
Aldrin John.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that since m2 is not synchronized, you might run into a concurrent access scenario in m2 and end up in inconsistent object states for open ( unlocked ) objects.
FYI - this kind of programming is not recommended.
 
Yuri Gadow
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to clarify a bit, the monitor for an object is not entered, no attempt is made to acquire the lock, unless a synchronized modifier or operator is encountered. So, as Kallambella indicated, m2 is not synchronized in that a direct call to it, from some other thread will <em>not</em> block even though the first thread holds the lock on C.
If all access to m2 is via m1, while not technically synchronized, access would be thread safe. However, to ensure this, you would need to make m2 private. Not a very elegant solution, and since Java monitors are re-entrant, you would probably want to declare both methods synchronized or have synchronized blocks within.
[This message has been edited by Yuri Gadow (edited June 19, 2001).]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!