开发者

Is getResourceAsStream() thread-safe?

开发者 https://www.devze.com 2023-03-14 18:03 出处:网络
I need to read a properties file containing some configuration data in a JSF web application. Right now the code looks like this

I need to read a properties file containing some configuration data in a JSF web application.

Right now the code looks like this

 private Properties getConfig() {
    Properties properties = new Properties();

    InputStream inputStream = null;
    try {
        inputStream = this.getClass().getResourceAsStream("/config.properties");

        try {
        properties.load(inputStream);
        } catch (IOExce开发者_高级运维ption e) {
        logger.error("Error while reading config properties", e);
        }

    } finally {
        if (inputStream != null) {
        try {
            inputStream.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        }
    }

    return properties;
 }

Is it safe to do it this way or can I run into concurrency issues when multiple threads are calling getConfig()?


No, that should be perfectly safe. I can't see any concurrency issues in there.

However, the exception handling might not be ideal - is it valid to return an empty properties object if you fail to load the config, or should you propagate the exception out of getConfig()? Up to you, really....

0

精彩评论

暂无评论...
验证码 换一张
取 消