سؤال

Is a static class kept along with it’s static variables in the memory after using it once, or is it instantiated along with every variable every time I use it?

To make it more real lets create an example.
Let’s say I want to make a language dictionary for my system not using singletons.
My static language class with 2 static variables:

package server;  
import java.util.Locale;  
import java.util.ResourceBundle;  

public abstract class Language {  
    private static Locale language = new Locale("en", "GB");  
    public static ResourceBundle dictionary = ResourceBundle.getBundle("dictionary_"+Language.language, Language.language);  

    public static void changeLanguage(Locale language){  
        Language.language = language;  
        Language.dictionary = ResourceBundle.getBundle("dictionary_"+Language.language, Language.language);  
    }  
}  

When I use it in the system to get a tekst value like so:

System.out.println(Language.dictionary.getString("system.name"));  

Will the whole class along with dictionary static variable stay in memory until I use it again, or will it be created again, and again eating my memory every time I do so?

هل كانت مفيدة؟

المحلول

Actually Static variables stored in a specific space in the memory called PermGen, this area holds you static variables once you used them. and if you want to use it again it will get them from that space with out re-creating them again.

But this space could get filled during the execution time, here the GC will start collect and delete some references from it, in this case if your variable got delete by GC and you want to use it again it will be created again.

You can read more about PermGen

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top