0

I am just following this answer and stucked. What I am doing is safeguarding my Singleton class being loaded twice with different class loader. I am not using any custom class loader. Is there any way to stop loading twice with URLClassLoader ?

my singleton class

package hacking;

public class Singleton {
    private static Singleton ref;
    private Singleton() {
    }
    public static synchronized Singleton getSingletonObject() {
        if (ref == null)
            ref = new Singleton();
        return ref;
    }
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}

I made a jar file out of this Singleton.java and loaded the same jar twice.

package com.foo;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class SingletonTest {

    public static void main(String[] args) throws Exception {

        URL url = new URL("file:\\D:\\foo\\singleton.jar");
        ClassLoader cl1 = new URLClassLoader(new URL[] { url }, null);
        ClassLoader cl2 = new URLClassLoader(new URL[] { url }, null);

        Class<?> singClass1 = cl1.loadClass("hacking.Singleton");
        Class<?> singClass2 = cl2.loadClass("hacking.Singleton");


        Method getInstance1 = singClass1.getDeclaredMethod("getSingletonObject", null);
        Method getInstance2 = singClass2.getDeclaredMethod("getSingletonObject", null);

        Object singleton1 = getInstance1.invoke(null);
        Object singleton2 = getInstance2.invoke(null);

        System.out.println(singleton1.hashCode());
        System.out.println(singleton2.hashCode()); 
   /* this is problem i am trying to solve, cause i get two different object
     for my singleton class. */

    }

}

how to safeguard my singleton class to load twice here? I need a common parent to load the class, but how I can implement in this scenario ?

Please help me with the code , I am not good in English.

Thanks for being nice and constructive.

Santanu Sahoo
  • 1,137
  • 11
  • 29

0 Answers0