我有一个场景,我必须连接到虚拟中心并获取数据。我实现了一个单例类,以便两个线程不能同时访问VC,因为它提供了并发访问问题。我的代码如下:从另一个类访问的单例类
public class Connector {
private static Connector instance ;
private Connector(String urlStr, String username, String password) {
connect(urlStr, username, password);
}
public static synchronized Connector getInstance(String urlStr, String username, String password) {
if (instance == null){
instance = new Connector(urlStr,username,password);
System.out.println("creating instance");
}
return instance ;
}
public void connect(String urlStr, String username, String password) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
//code to connect to VC
}
} catch (RuntimeException e) {
connectException = e;
} finally {
Thread.currentThread().setContextClassLoader(cl);
}
}
public void disconnect() throws RuntimeFault, RemoteException {
//code for disconnect
}
}
}
我以下列方式称为从另一个类:
Connector c = Connector.getInstance(dburl, dbuser, dbpass);
c.connect(dburl, dbuser, dbpass);
//code for getting data
c.disconnect();
现在,如果我有2个同时请求获得来自viruatal中心的数据,其中一人失败说“会话未通过身份验证”。 你能帮助我们以更好的方式来处理这个问题吗?因为总是使用相同的实例,我们如何区分不同的虚拟中心。
你做得完全错误,不要使用单身,如果你不能 –
换句话说就是@RomanC说的。 –
阅读:https://sites.google.com/site/steveyegge2/singleton-considered-stupid –