How to prevent multiple instances of objects of a particular class

MyInterface intf = (MyInterface) Class.forName(className).newInstance();

I have a specific piece of code that will create new interfaces on demand using the above call and call a specific method. All implementation classes usually contain many variables final staticand static initialization code, which I would like to run only once in my life.

But since I use the call to newInstance (), I get the impression that the old object gets GCed, and the class is initialized again and, therefore, all static variables.

To avoid this, I would like to put this in the cache so that these classes are not built again and therefore would be initialized once during its lifetime. (Note: My interfaces are thread safe).

Should I just put this in Hashtableand just see it or is it better to process the cache?

+3
source share
6 answers

All implementation classes usually contain many finite static variables and static initialization code that I would only like to run once in a lifetime.

But since I use newInstance () call, I get the impression that the old object gets GCed and the class is initialized again and, therefore, all static variables.

, . - . . , . , GCed : -).

:

, . , GC. , , , , , . ...

. :

?

+6

, , , - , , newInstance(). , , : AFAIK , . . question.

+3

- :

private static Map<String, Object> cache = 
    new ConcurrentHashMap<String, Object>();

@SuppressWarnings("unchecked")
public static <T> T getImplementation(final String implementationClass){
    T result;
    synchronized(cache){
        result = (T) cache.get(implementationClass);
        if(result == null){
            try{
                result =
                    (T) Class.forName(implementationClass).newInstance();
            } catch(final Exception e){
                // error handling here
            }
            cache.put(implementationClass, result);
        }
    }
    return result;
}

, ( , )

FooService service = getImplementation("com.mycompany.FooServiceImpl");

Guava, :

private static Map<String, Object> cache =
     new MapMaker().makeComputingMap(
         new Function<String, Object>(){

            @Override
            public Object apply(final String input){
                try{
                    return Class.forName(input).newInstance();
                } catch(final Exception e){
                    // error handling here
                }
            }
         });

@SuppressWarnings("unchecked")
public static <T> T getImplementation(final String implementationClass){
    return (T) cache.get(implementationClass);
}
+2

.

static final Map<String, Object> instances = new HashMap<String, Object>();

public static Object getInstance(String name) {

    if (name == null) {
        return null;
    }
    Object obj = null;

    synchronized (ClassName.class) {
        try {
            obj = instances.get(name);
            if (obj == null) {
                obj = Class.forName(name).newInstance();
                instances.put(name, obj);
            }
        } catch (ClassNotFoundException e) {
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        }
    }
    return obj;
}
+2
source
+1
source

This is called Singleton .
Using this template, there will be only one instance of your class.
There are some exceptions, however for most purposes you will only have one instance.

0
source

All Articles