最近在学习Java AIO操作时,出现如下异常

比较奇怪的是,该异常仅仅在两个操作间隔非常短的时候,才会出现。根据调式与排查,发现问题出现在AsynchronousSocketChannel的connect方法调用上。
/**
* Connects this channel.
*
* <p> This method initiates an operation to connect this channel. This
* method behaves in exactly the same manner as the {@link
* #connect(SocketAddress, Object, CompletionHandler)} method except that
* instead of specifying a completion handler, this method returns a {@code
* Future} representing the pending result. The {@code Future}'s {@link
* Future#get() get} method returns {@code null} on successful completion.
*
* @param remote
* The remote address to which this channel is to be connected
*
* @return A {@code Future} object representing the pending result
*
* @throws UnresolvedAddressException
* If the given remote address is not fully resolved
* @throws UnsupportedAddressTypeException
* If the type of the given remote address is not supported
* @throws AlreadyConnectedException
* If this channel is already connected
* @throws ConnectionPendingException
* If a connection operation is already in progress on this channel
* @throws SecurityException
* If a security manager has been installed
* and it does not permit access to the given remote endpoint
*/
public abstract Future<Void> connect(SocketAddress remote);
此处connect为异步方法,调用connect时,可能并没有成功建立连接,从而导致出现上述异常。
解决措施:
1、显示调用get,通过阻塞的方式,获取连接。

2、通过如下connect方法,通过第三个参数,在完成连接连接时,进行后续操作。
public abstract <A> void connect(SocketAddress remote,
A attachment,
CompletionHandler<Void,? super A> handler);

本文探讨了在JavaAIO操作中遇到的异常问题,特别是当AsynchronousSocketChannel的connect方法在短时间内连续调用时出现的异常。文章详细分析了异常产生的原因,并提供了两种解决方案:一是通过阻塞方式显式调用get方法获取连接;二是使用带有CompletionHandler的connect方法,以便在连接完成后执行后续操作。
7327

被折叠的 条评论
为什么被折叠?



