关于Singleton的使用。


public static ServiceLocator getInstance() throws NamingException {
if (instance == null) {
Properties props = getClusterCfg();
instance = new ServiceLocator(props.getProperty("url"),props.getProperty("user"),props.getProperty("pwd"));
}
return instance;
}


// 在此输入java代码

如上所示,我如果不对这个方法synchronized,是否就可以让它同时作为EJB和web层的服务查找。而不用像petstore那样在ejb和web分别放一个servicelocator?

自己定一下

建议使用


private static ServiceLocator instance;
static {
instance = ...;
}

这样你的方法就不需要同步了,只要return instance;就好了。

谢谢您的回复*^-^*
您说的正是petstore的web层所使用的
但是,它的servicelocator在web层和ejb层是不同的
因为在ejb层是忌讳用Singleton的。所以,我在写这个ServiceLocator的时候就想只写一个ServiceLocator,同时在ejb层和web层使用。
所以,我把banq先生说的那个需要注意的synchronized给去掉了,这样在ejb层是不是也可以创建多个实例了?

这样会不会有问题?

确切的说,是创建了多个实例,不过这是一种浪费。

谢谢