Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() ???

like image 931
Michael Avatar asked Dec 21 '22 01:12

Michael


2 Answers

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.

like image 100
Jon Skeet Avatar answered Dec 23 '22 13:12

Jon Skeet


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

like image 33
Brian Roach Avatar answered Dec 23 '22 13:12

Brian Roach