Java synchronized static methods: lock on object o

2019-01-01 03:16发布

The Java Tutorials say: "it is not possible for two invocations of synchronized methods on the same object to interleave."

What does this mean for a static method? Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object?

8条回答
孤独总比滥情好
2楼-- · 2019-01-01 03:46

For those who are not familiar static synchronized method locked on class object e.g. for string class its String.class while instance synchronized method locks on current instance of Object denoted by “this” keyword in Java. Since both of these object are different they have different lock so while one thread is executing static synchronized method , other thread in java doesn’t need to wait for that thread to return instead it will acquire separate lock denoted byte .class literal and enter into static synchronized method.

查看更多
流年柔荑漫光年
3楼-- · 2019-01-01 03:50

Unless you implement g() as follows:

g() {
    synchronized(getClass()) {
        ...
    }
}

I find this pattern useful also when I want to implement mutual exclusion between different instances of the object (which is needed when accesing an external resource, for example).

查看更多
登录 后发表回答