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

时间:2017-06-15 19:21:01

标签: java try-with-resources autocloseable

我需要打开N个多播套接字(其中N来自参数列表的大小)。然后,我将相同的数据发送到循环中的每个N个套接字,最后,关闭每个套接字。我的问题是,如何使用try-with-resources块执行此操作?以下是我如何使用单一资源执行此操作:

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
    ...
}

我能想到用多个端口执行此操作的唯一方法如下:

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
        }
    }
}

有没有更简洁的方法来实现这一目标,或者我提出的解决方案是否合理?

4 个答案:

答案 0 :(得分:2)

以递归方式执行以保证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.
    }
  }
}

答案 1 :(得分:1)

你正在做的事情几乎和它一样好。

你可以创建一个AutoCloseable通用多关闭器,它包含一个List<AutoCloseable>,并接受一个构造函数参数,一个可关闭的计数和一个要调用的工厂来创建每个可关闭的,然后关闭它们所有当它被调用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
    }
}

......但这可能是一种矫枉过正。

答案 2 :(得分:0)

使用ArrayList存储MulticastSocket个实例有什么意义?

你这么说:

  

然后,我将相同的数据发送到a中的每个N个套接字   循环,最后,关闭每个套接字。

因此,您可以在循环中创建它们,并为每次迭代发送相同的处理 要做到这一点,你应该稍微改变你的设计 MulticastSocket的处理任务可以通过功能接口执行,该接口也允许指定要使用的端口。

例如:

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

您可以使用一个方法,将此功能接口作为参数来应用处理:

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

最后,从客户端代码,您可以使用lambda:

创建一个socketProcessor实例
SocketProcessor socketProcessor = (MulticastSocket socket) -> {
    socket.send(...);
    socket.send(...);
};

然后你可以在端口上循环,以便使用合适的端口和刚刚创建的SocketProcessor实例调用processSocket:

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

这个解决方案没有必要缩短(没有真正更长),但它更清晰 两个主要问题是分开的:

    执行锅炉铭牌代码的
  • processSocket(SocketProcessor)

  • SocketProcessor定义具体任务。

答案 3 :(得分:0)

受到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
                }
            }
        }
    }

}