简体   繁体   中英

synchronized static methods

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

A synchronized static method is synchronized on the class's corresponding Class object, so it's a different lock than the one used by instance methods. Clearly, the static method doesn't have access to this . So your f1() and f2() methods are not synchronized against each other, only against other static or other instance methods of the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM