简体   繁体   English

Java Try-With-Resources未知资源计数

[英]Java Try-With-Resources Unknown Resource Count

I have a need to open N multicast sockets (where N comes from the size of an argument list). 我需要打开N个多播套接字(其中N来自参数列表的大小)。 I will then send the same data to each of the N sockets within a loop, and finally, close each socket. 然后,我将在循环中将相同的数据发送到N个套接字中的每个套接字,最后关闭每个套接字。 My question is, how do I do this using the try-with-resources block? 我的问题是,如何使用try-with-resources块执行此操作? 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? 有没有更简洁的方法来完成此操作,或者我提出的解决方案是否还不错?

Do it recursively to keep the guarantees of try-with-resources: 递归执行以确保尝试资源的保证:

void foo(List<Integer> ports, List<Socket> sockets) {
  if (sockets.size() == ports.size()) {
    // Do something with your sockets.
  } else {
    try (Socket s = new MulticastSocket(ports.get(sockets.size())) {
      sockets.add(s);
      foo(ports, sockets);
      // You could call sockets.remove(sockets.size()-1) here.
      // Not convinced whether it's worth it.
    }
  }
}

What you are doing is practically as good as it gets. 实际上,您所做的一切都很好。

You could create an AutoCloseable general-purpose multi-closer which contains a List<AutoCloseable> and accepts as a constructor parameter a count of closeables and a factory to invoke to create each closeable, and then close them all when its close() is invoked, so that you can use it like this: 您可以创建一个包含List<AutoCloseable>AutoCloseable通用型多重关闭器,并接受一个可计数对象的数量作为构造函数参数,并接受一个工厂来创建每个可封闭对象,然后在调用其close()时将其全部close() ,这样您就可以像这样使用它:

try( MultiCloser<MulticastSocket> multiCloser = 
         new MultiCloser<>( ports.size(), i -> new MulticastSocket( ports.get( i ) ) )
{
    for( MulticastSocket socket : multiCloser.getItems() )
    {
        do something with the socket
    }
}

...but it would probably be an overkill. ...但这可能是一个过大的杀伤力。

What is the point to use an ArrayList to store the MulticastSocket instances ? 使用ArrayList存储MulticastSocket实例有什么意义?

You said that : 你之前这么说 :

I will then send the same data to each of the N sockets within a loop, and finally, close each socket. 然后,我将在循环中将相同的数据发送到N个套接字中的每个套接字,最后关闭每个套接字。

So you can create them in a loop and send for each iteration the same processing. 因此,您可以循环创建它们,并为每个迭代发送相同的处理。
To do it, you should a little change your design. 为此,您应该稍微更改一下设计。
The processing task of the MulticastSocket could be performed by a functional interface that allows also to specify the port to use. MulticastSocket的处理任务可以由功能接口执行,该功能接口还允许指定要使用的端口。

For example : 例如 :

@FunctionalInterface
public interface SocketProcessor {
    void process(MulticastSocket multicastSocket) ;
}

You could have a method that takes as parameter this functional interface to apply the processing : 您可能有一个以该功能接口为参数的方法来应用处理:

public static void processSocket(SocketProcessor socketProcessor, Integer port) throws IOException {
  try (final MulticastSocket socket = new MulticastSocket(port)) {
    socketProcessor.process(socket);
  }
}

At last from the client code, you could create a socketProcessor instance with a lambda : 最后,从客户端代码,您可以创建一个带有lambda的socketProcessor实例:

SocketProcessor socketProcessor = (MulticastSocket socket) -> {
    socket.send(...);
    socket.send(...);
};

And then you could loop on the ports in order to invoke processSocket with the suitable port and the SocketProcessor instance just created : 然后,您可以在端口上循环以使用合适的端口和刚刚创建的SocketProcessor实例调用processSocket:

for (final Integer port : ports) {
    try {
      processSocket(socketProcessor, port);
    } catch (IOException e) {
      // do processing
    }
}

This solution is not necessary shorter (without being really longer) but it is really clearer. 此解决方案不一定要更短(实际上并不需要更长),但是确实更清晰。
The two main concerns are separated : 两个主要问题是分开的:

  • processSocket(SocketProcessor) that performs the boiler plate code processSocket(SocketProcessor)执行样板代码

  • SocketProcessor that defines the concrete task. 定义具体任务的SocketProcessor

Inspired by the idea proposed by Mike Nakis, I came up with the following class... 受到Mike Nakis提出的想法的启发,我提出了以下课程...

package myNamespace;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import myNamespace.ThrowingFunction;
import myNamespace.ThrowingSupplier;

/** Collection of AutoCloseable objects */
public class ResourceCollection<T extends AutoCloseable>
        implements Iterable<T>, AutoCloseable {

    /** Resources owned by this instance */
    private final List<T> myResources;

    /**
     * Constructor
     * @param allocator Function used to allocate each resource
     * @param count     Number of times to call the allocator
     * @throws E Thrown if any of the allocators throw
     */
    public <E extends Throwable> ResourceCollection(
            final ThrowingSupplier<T, E> allocator, final int count)
            throws E {
        myResources = new ArrayList<>(count);
        try {
            while (myResources.size() < count) {
                final T resource = allocator.getThrows();
                myResources.add(resource);
            }
        } catch (final Throwable e) {
            close();
            throw e;
        }
    }

    /**
     * Constructor
     * @param allocator Function used to allocate each resource
     * @param input     List of input parameters passed to the allocator
     * @throws E Thrown if any of the allocators throw
     */
    public <U, E extends Throwable> ResourceCollection(
            final ThrowingFunction<U, T, E> allocator, final Collection<U> input)
            throws E {
        myResources = new ArrayList<>(input.size());
        try {
            for (final U value : input) {
                final T resource = allocator.applyThrows(value);
                myResources.add(resource);
            }
        } catch (final Throwable e) {
            close();
            throw e;
        }
    }

    /**
     * Gets the number of resources in the collection
     * @return The number of resources in the collection
     */
    public int size() {
        return myResources.size();
    }

    /**
     * Gets whether the collection contains no resources
     * @return Whether the collection contains no resources
     */
    public boolean isEmpty() {
        return myResources.isEmpty();
    }

    /**
     * Gets the resource at index i
     * @param i The index of a resource, in the range [0, size())
     * @return The resource at index i
     */
    public T get(final int i) {
        return myResources.get(i);
    }

    @Override
    public Iterator<T> iterator() {
        return myResources.iterator();
    }

    @Override
    public void close() {
        final ListIterator<T> resourceIter =
                myResources.listIterator(myResources.size());
        while (resourceIter.hasPrevious()) {
            final T resource = resourceIter.previous();
            if (resource != null) {
                try {
                    resource    .close ();
                    resourceIter.remove();
                } catch (final Throwable t) {
                    // Eat the exception
                }
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM