[英]Java Try-With-Resources Unknown Resource Count
我需要打開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
}
}
}
有沒有更簡潔的方法來完成此操作,或者我提出的解決方案是否還不錯?
遞歸執行以確保嘗試資源的保證:
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.
}
}
}
實際上,您所做的一切都很好。
您可以創建一個包含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
}
}
...但這可能是一個過大的殺傷力。
使用ArrayList
存儲MulticastSocket
實例有什么意義?
你之前這么說 :
然后,我將在循環中將相同的數據發送到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
。
受到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.