I am trying to build an RMI Client/Server in the same JVM but I am facing a problem while using the same Singleton instance for both Client and Server when running each of them. For both client and the server a distinct instance of my singleton is created. After reading a bit about the potential problems a developer may face while implementing the Singleton design pattern, I figured out that is mainly due to the different ClassLoaders of both Client and Server although they are running on the same JVM (Or there's may be some other reason I couldn't see?!). So after reading some recommended articles like Singleton Pattern in Java and Java Reflection I finally implemented this solution which I am not sure if it is the right way to do and which throws by the way an exception :
//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 = Controller.class.getClassLoader().getParent();
if(classLoader == null)
classLoader = Controller.class.getClassLoader();
return classLoader;
}
Any help will be more than welcome. Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire