I have a need to open N multicast sockets (where N comes from the size of an argument list). I will then send the same data to each of the N sockets within a loop, and finally, close each socket. My question is, how do I do this using the try-with-resources block? The following is how I would do this with a single resource:
final int port = ...;
try (final MulticastSocket socket = new MulticastSocket(port)) {
// Do a bunch of sends of small packet data over a long period of time
...
}
The only way I can think of to do this with multiple ports is the following:
final List<Integer> ports = ...;
final List<MulticastSocket> sockets = new ArrayList<>(ports.size());
try {
for (final Integer port : ports) {
sockets.add(new MulticastSocket(port));
}
// Do a bunch of sends of small packet data over a long period of time
...
} finally {
for (final MulticastSocket socket : sockets) {
try {
socket.close();
} catch (final Throwable t) {
// Eat the exception
}
}
}
Is there a more concise way to accomplish this, or is my proposed solution as good as it gets?