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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With