我正在尝试在同一个JVM中构建一个RMI客户端/服务器但是在运行每个客户端和服务器时同时使用相同的Singleton实例时遇到问题。对于客户端和服务器,都会创建我的单例的不同实例。在阅读了一些开发人员在实现Singleton设计模式时可能遇到的潜在问题后,我发现这主要是由于Client和Server的不同ClassLoader,尽管它们运行在同一个JVM上(或者那里有)可能是我无法看到的其他原因?!)。因此,在阅读了一些推荐的文章,如Singleton Pattern in Java和Java Reflection后,我终于实现了这个解决方案,我不确定它是否是正确的方法,并且通过异常的方式抛出:
//This is the method used to get my Singleton (i.e: Controller) instance
public static Controller getInstance() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class obj = getClassLosader().loadClass(Controller.class.getName());//java.lang.ClassNotFoundException thrown here
Method getInstanceMethod = obj.getDeclaredMethod("getInstanceSingleton", new Class[] { });
Object absoluteController = getInstanceMethod.invoke(null, new Object[] { } );
return (Controller)absoluteController;
}
public static Controller getInstanceSingleton(){
if(controller==null)
controller = new Controller();
return controller;
}
private static ClassLoader getClassLosader() throws ClassNotFoundException {
//ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// doesn't solve the problem either
ClassLoader classLoader = Controller.class.getClassLoader().getParent();
if(classLoader == null)
classLoader = Controller.class.getClassLoader();
return classLoader;
}
任何帮助都将受到欢迎。提前谢谢。