I'm very confused because of Java's synchronized concept.
Let's assume the below class:
class MyClass {
public synchronized void foo() { //do something }
public void bar() {
synchronized(this) { //do something }
}
public void normal() { //do something }
}
As far as I know, the foo and bar methods work the same.
But, after thread A enters the bar method and synchronizes the instance by synchronized(this), can any thread call the normal method?
As far as I know, some threads can call the normal method regardless of calling the foo method. But I'm not sure when the bar method is called because it synchronized an instance.
Also, let's assume the below method:
class StaticMyClass {
public static synchronized void fooStatic() { //do something }
publi static void barStatic() {
synchronized(StaticMyClass.class) { //do something }
}
public static void normalStatic() { //do something }
}
Here, there is the same question. After thread A enters the critical section, which is synchronized(StaticMyClass.class) or the fooStatic method, can any thread call normalStatic?
I think that fooStatic and normalStatic can be called independently, but barStatic and normalStatic can't. If it is wrong, why?
I appreciate your help.
Edit:
My confused point is that I am not sure that synchronized(this) is same as synchronized(myClassInstance).
MyClass my = new MyClass();
synchronized(my) {
//do something, Any other thread can't access my.normal(), is it right?
}
class MyClass {
public synchronized void foo() { //do something }
public void bar() {
synchronized(this) {
//do something, isn't this same as above synchronized(my)?
}
}
public void normal() { //do something }
}