Normally to read contents from a file present in your resources directory, we can do it by opening up an Input Stream.
this.getClass().getClassLoader().getResourceAsStream("yourJsonFile.json"); this works fairly well when calling it synchronously.
In case of handling this concurrently, it throws an I/O Exception with the below message.
Too many open files
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:91)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
at java.nio.file.Files.newInputStream(Files.java:152)
at java.nio.file.Files.newBufferedReader(Files.java:2784)
at java.nio.file.Files.lines(Files.java:3744)
at java.nio.file.Files.lines(Files.java:3785)
To make it a little comprehensive, assume we are reading a file using an InputStream and closing it as soon as all lines are read from the file. In this case one I/O port is open while the file is being read. But, when concurrent calls happen it tries to open multiple ports at a time. This not only blocks the progress of the program but also hampers the performance as the I/O operation is a little higher on the time consumption side.
In order to come around of this situation, we can cache the IO stream by enclosing it into a compatible Data Structure, a HashMap could be ideal. Have a method which can return the HashMap. Now whenever we need to read the file all we need to do is call this method to have your file contents readily available for you.
This is one of the approach which is currently handling this scenario.
Any other approaches which are perhaps more efficient?