多次读取属性文件会占用大量内存吗?

时间:2011-02-28 23:16:51

标签: java memory properties

我有一个读取属性文件的类。请看下面。 当应用程序运行时,方法readProperties()被多次调用,这是否意味着这里存在内存问题?


public class PropertyReader {
    private static Properties   configKeyValuePairs         = null;
    private static String       configPropertiesFileName    = "Config.properties";

    static void readProperties() throws FileNotFoundException, IOException {    
        configKeyValuePairs = new Properties();
        InputStream input = ConfigReader.class
                .getResourceAsStream(configPropertiesFileName);

        configKeyValuePairs.load(input);

        input.close();
    }

   static String getUserName(){
       //return user name which is from the properties file.    
    }
}





3 个答案:

答案 0 :(得分:2)

假设您的属性文件永远不会更改,您可以执行以下操作:

public class MyApplicationConfiguration {
    private static Properties   configKeyValuePairs         = new Properties();
    private static String       configPropertiesFileName    = "Config.properties";

    static {
        InputStream input = null;
        try {
            input = MyApplicationConfiguration.class
                .getResourceAsStream(configPropertiesFileName);

            configKeyValuePairs.load(input);

        } catch (IOException e) {
            // Deal with not being able to load config, could be a fatal error!
        } finally {
            if (input != null) {
                input.close();
            }
        }
    }

    public static String getUsername() {
        // ...
    }

    // Implement getters for other configuration key-value pairs
    // DO NOT let configKeyValuePairs be returned to anyone
}

答案 1 :(得分:2)

加载属性对象一次,并将其存储为类成员。

我发现很难相信你会因为它而有记忆问题。

如果你发现自己这样做了,那么你总能回来重新思考它,但不要过早地优化可能不存在的问题。

答案 2 :(得分:1)

是的,可能存在非常大的内存问题,具体取决于是否存在包含对新创建的属性对象的引用的调用类。

尝试这样的事情:

public class PropertyReader {
    private static       Properties   configKeyValuePairs         = null;
    private static final String       configPropertiesFileName    = "Config.properties";


    public static void readProperties() throws FileNotFoundException, IOException { 
        if(null == configKeyValuePairs){
            InputStream input;
            synchronized(PropertyReader.class){
                try{
                    configKeyValuePairs = new Properties();
                    input = PropertyReader.class
                        .getResourceAsStream(configPropertiesFileName);

                    configKeyValuePairs.load(input);
                }finally{
                    //this can still throw ioexception!
                    if(null != input){
                        input.close();
                    }
                }
          }
    }
}