I'm creating multiple streams which I have to access in parallel (or possibly-parallel). I know how to make a try-with-resources when the amount of resources is fixed at compile-time, but what if the amount of resources is determined by a parameter?
I have something like this:
private static void foo(String path, String... files) throws IOException {
@SuppressWarnings("unchecked")
Stream<String>[] streams = new Stream[files.length];
try {
for (int i = 0; i < files.length; i++) {
final String file = files[i];
streams[i] = Files.lines(Paths.get(path, file))
.onClose(() -> System.out.println("Closed " + file));
}
// do something with streams
Stream.of(streams)
.parallel()
.flatMap(x -> x)
.distinct()
.sorted()
.limit(10)
.forEach(System.out::println);
}
finally {
for (Stream<String> s : streams) {
if (s != null) {
s.close();
}
}
}
}