Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is getResourceAsStream() thread-safe?

Tags:

java

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 (IOException 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()?

like image 893
Sylar Avatar asked Feb 24 '26 07:02

Sylar


1 Answers

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....

like image 154
skaffman Avatar answered Feb 26 '26 01:02

skaffman