Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is getResourceAsStream thread safe?

Code on a web server:

public byte[] loadData() {
    byte[] data = null;
    try(final InputStream resourceStream = getClass().getResourceAsStream("data.bin")) { 
        data = ByteStreams.toByteArray(resourceStream); //ByteStreams is from Guava library
    } catch (IOException e) {
        e.printStackTrace();
    }
    return data;
}

Is there a problem with several threads opening a stream on a resource and reading its content? In this case the resource is a data file contained in a jar.

On windows concurrently reading the resource was not a problem. However this is not efficient so I opted to use a WeakReference and double-checked locking to load the data only once.

like image 606
Roland Avatar asked Nov 10 '22 01:11

Roland


1 Answers

The only state that may possibly be shared between your threads is the InputStream returned by getResourceAsStream(String). Let's check if it's the same object.

Here's a very simple test you can use to try this out yourself:

InputStream first = getClass().getResourceAsStream("data.bin")
InputStream second = getClass().getResourceAsStream("data.bin")
System.out.println(first == second);

This will (typically) return false. Since they aren't the same object, you have no thread safety issues.


I say typically because getResourceAsStream depends on the underlying ClassLoader that loaded the Class instance returned by getClass(). So, unless you're writing and using your own (or 3rd party) ClassLoader objects, you'll be fine.

like image 189
Sotirios Delimanolis Avatar answered Nov 15 '22 11:11

Sotirios Delimanolis