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?
class A
{
publicsynchronizedvoid m1()
{
}
}
is just the same as
class A
{
publicvoid m1()
{
synchronized(this)
{
}
}
}
Then, why 'synchronized' keyword on method is needed?
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.
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.
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.