If I have a class with a number of synchronized methods, some of them are static and some of them not:
public class A {
public static void synchronized f1() {}
public void synchronized f2() {}
}
what happens when one thread calls f1() and second calls f2(), it means how they synchronized with each other. and what happens if one tread calls f1() and f1() calls f2() ???
They're not synchronized with each other at all. The static method is synchronized on A.class
, the second is synchronized on this
. So it's (almost) as if you'd written:
public class A {
public static void f1() {
synchronized(A.class) {
...
}
}
public void f2() {
synchronized(this) {
...
}
}
}
and what happens if one tread calls f1() and f1() calls f2()
Then that thread will own both monitors during f2
. You should be careful before you do this, as if you take out the locks in the reverse order elsewhere, you'll get a deadlock.
Personally I would urge you to avoid synchronized methods entirely. Instead, synchronize on private, final fields which are only used for locking. That means that only your class is able to acquire the relevant monitors, so you can reason much more carefully about what occurs while the locks are held, and avoid deadlocks etc.
A synchronized static method synchronizes on the Class object, rather than an instance.
f1()
and f2()
can be called by two separate threads and will execute simultaneously.
See: http://java.sun.com/docs/books/jls/third_edition/html/classes.html#260369
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With