Много раз читает файлы свойств много памяти? - PullRequest
1 голос
/ 01 марта 2011

У меня есть класс, который читает файл свойств. Пожалуйста, смотрите ниже. Метод 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 ]

2 голосов
/ 01 марта 2011

Если ваш файл свойств никогда не меняется, вы можете сделать следующее:

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
}
2 голосов
/ 01 марта 2011

Загрузите объект свойств один раз и сохраните его в классе.

Мне трудно поверить, что из-за этого у вас будут проблемы с памятью.

Если вы узнаете, что делаете, то вы всегда можете вернуться и переосмыслить его, но не преждевременно оптимизируйте проблему, которая, вероятно, не существует.

1 голос
/ 01 марта 2011

Да, может быть очень большая проблема с памятью, в зависимости от того, существуют ли вызывающие классы, которые содержат ссылку на вновь созданный объект свойств.

Попробуйте что-то вроде этого:

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();
                    }
                }
          }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...