最近在学习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);