Why 'synchronized' keyword on method is needed?

class A

{

publicsynchronizedvoid m1()

{

}

}

is just the same as

class A

{

publicvoid m1()

{

synchronized(this)

{

}

}

}

Then, why 'synchronized' keyword on method is needed?

[858 byte] By [WHOSNEXT] at [2007-9-26 2:27:23]
# 1
I'm not sure if it really is 100% the same thing, but if so then it just might be syntactic sugar.GreetsPuce
Puce at 2007-6-29 9:41:34 > top of Java-index,Core,Core APIs...
# 2

Maybe its not needed, but its handy. Why would you not want it? - the first version you gave us is certainly neater, and easier to read - you can scan a class and find synchronized methods or use reflection to pick them out. It appears in the Javadoc too.

Its almost like the abstract keyword - all classes that contain abstract methods are implicitely abstract yet you are forced to explicitely declare them as so in the class signature. Why? - so that users of your classes don't have to pick through all your code to work out whether an object of that class can be instantiated - you just have to look at the class signature.

mattbunch at 2007-6-29 9:41:34 > top of Java-index,Core,Core APIs...
# 3

In this example its the same, but if you had more than one method in your class it would not.

In the first example you are only synchronizing on the method ml(). If you had another method, that could also be accessed from another thread while you were in ml.

In the second example you are synchronizing on the entire object, so you would not be able to access any other methods while you were in ml.

Its subtle, but could make a difference to performance.

SteveWink at 2007-6-29 9:41:34 > top of Java-index,Core,Core APIs...
# 4
I've just re-read my Java book and realised that a synchronized method will cause a lock on the class, not just the method. Ooops.
SteveWink at 2007-6-29 9:41:34 > top of Java-index,Core,Core APIs...
# 5
a lock on the object, not on the class. Double Oooops ;-)GreetsPuce
Puce at 2007-6-29 9:41:34 > top of Java-index,Core,Core APIs...
# 6

For your example, it would be the same.

But I think the difference is when you want to synchronize code involving multiple objects.

For example,

Object mutex = new ...;

ClassA A = new ...;

ClassB B = new ...;

// In one thread

synchronized(mutex)

{

A.method();

}

// In another thread

synchronized(mutex)

{

B.method();

}

Even if ClassA's methods are synchronized, and ClassB's methods are synchronized, they are not synchronized with each other. So you use another object to synchronize on.

alee1010 at 2007-6-29 9:41:34 > top of Java-index,Core,Core APIs...
# 7
Whoops forgot to finish... I don't think it is really needed in the method declaration, I think Puce and mattbunch are right, it's just easier and provides documentation.
alee1010 at 2007-6-29 9:41:34 > top of Java-index,Core,Core APIs...