java静态方法 同步,如何在java中同步静态方法

I come up with this question when implementing singleton pattern in Java. Even though the example listed below is not my real code, yet very similar to the original one.

public class ConnectionFactory{

private static ConnectionFactory instance;

public static synchronized ConnectionFactory getInstance(){

if( instance == null ){

instance = new ConnectionFactory();

}

return instance;

}

private ConnectionFactory(){

// private constructor implementation

}

}

Because I'm not quite sure about the behavior of a static synchronized method, I get some suggestion from google -- do not have (or as less as possible) multiple static synchronized methods in the same class. I guess when implementing static synchronized method, a lock belongs to Class object is used so that multiple static synchronized methods may degrade performance of the system.

Am I right? or JVM use other mechanism to implement static synchronized method? What's the best practice if I have to implement multiple static synchronized methods in a class?

Thank you all!

Kind regards!

解决方案

The best approach (which makes as few changes in your code as possible) is to do like this:

public class ConnectionFactory{

private static ConnectionFactory instance = new ConnectionFactory();

public static ConnectionFactory getInstance(){

return instance;

}

private ConnectionFactory(){

}

}

As you can see, there is no real need in getInstance method now, so you can simplify the code to:

public class ConnectionFactory{

public static final ConnectionFactory INSTANCE = new ConnectionFactory();

private ConnectionFactory(){

}

}

UPD about synchronization: the best way is synchronizing on a lock which is not visible to outer classes, i.e.:

public class ConnectionFactory{

private static final Object lock = new Object();

public static void doSmth() {

synchronized (lock) {

...

}

}

public static void doSmthElse() {

synchronized (lock) {

...

}

}

}

There are many discussions about "why synchronizing on this is a bad idea" (like this one), I think that the same is actual for synchronizing on class.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值