java Netty:使用多个事件循环的并发问题
我有一个客户端连接到n个不同的服务器。所以,我创建了n个不同的频道
因为我的服务器超过5000台。我使用10个事件循环,只有一个事件循环组。此外,每个通道都有单独的管道
我已经知道,如果我使用一个事件循环,将不会出现并发问题,而且我还没有在10个事件循环上看到任何并发问题。我的问题是:
我会在下面代码的第healthTargets.storeHealthyTarget(InetAddress.getByName(remoteAddress));
行出现并发问题吗?为什么
我怀疑会出现并发问题。因为,如果多个事件循环没有访问它,那么使用多个事件循环有什么意义
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws UnknownHostException {
if(channelHandlerContext.channel().remoteAddress() != null)
{
String remoteAddress = remoteAddress(channelHandlerContext.channel().remoteAddress().toString());
if (httpObject instanceof HttpResponse) {
HttpResponseStatus responseStatus = ((HttpResponse)httpObject).getStatus();
if (responseStatus.code() == HttpResponseStatus.OK.code())
{
healthTargets.storeHealthyTarget(InetAddress.getByName(remoteAddress));
}
}
}
}
这里healthTargets.storeHealthyTarget
只是使用HashSet来存储ip,healthTargets是一个单例类
# 1 楼答案
如果在不同的EventLoops之间共享
Set
的同一个实例(您似乎是这样做的),您将遇到问题。这是因为不同的通道可能会在不同的EventLoops和其他线程上运行。这样做的效果是,您需要确保对healthTargets
线程的访问是安全的这与其他多线程程序没有什么不同