static and non-static Synchronized methods - difference.
My Understanding : If a static method is synchronized, then only one static synchronized method in the class will be accessible at any point of time to the threads. So if there were two threads and one of them is accessing a non-static synchronized method, and the other is accessing a static synchronized method, both threads should comfortably have access to those methods.
Other statement : If a static synchronized method is accessed by a thread, then even non-static synchronized methods are not available to other threads.
Which one is true of above 2 statements, if u could give an example and explanation to above query. Also, If someone gives the difference between static and non-static Synchronized methods. Thanks all.
> My Understanding : If a static method is
> synchronized, then only one static synchronized
> method in the class will be accessible at any point
> of time to the threads. So if there were two threads
> and one of them is accessing a non-static
> synchronized method, and the other is accessing a
> static synchronized method, both threads should
> comfortably have access to those methods.
>
Correct
> Other statement : If a static synchronized method is
> accessed by a thread, then even non-static
> synchronized methods are not available to other
> threads.
Wrong
JLS section 17.13:
http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html
A synchronized method (?.4.3.6) automatically performs a lock action when it is invoked; its body is not executed until the lock action has successfully completed. If the method is an instance method, it locks the lock associated with the instance for which it was invoked (that is, the object that will be known as this during execution of the body of the method). If the method is static, it locks the lock associated with the Class object that represents the class in which the method is defined. If execution of the method's body is ever completed, either normally or abruptly, an unlock action is automatically performed on that same lock.
A static synchronized object is synchronized on the class' Class object (Foo.class). A non-static synchronized method is synchronized on the object itself (this). Thus your first statement is true.
It should be noted that in the following class foo1 and foo2 are semantically identical, as are bar1 and bar2.
public Class FooBar {
public static synchronized void foo1() {
doWhatever();
}
public static void foo2() {
synchronized (FooBar.class) {
doWhatever();
}
}
public synchronized void bar1() {
doWhatever();
}
public void bar2() {
synchronized(this) {
doWhatever();
}
}
}
See what the [url=http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.3.6]JLS says about synchronized methods[/url].