问题
Lets say we have some kind of pub/sub protocol. When someone is connecting and subscribing, we can save channel in Map, List or ChannelGroup:
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
log.debug("Client connected: {}", ctx.channel().remoteAddress());
clients.add(ctx);
}
After that, when some message has come or some event has happened, I can notify clients:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
log.debug("Client {} published msg: {}", ctx.channel().remoteAddress(), msg);
clients.foreach(client -> client.getChannel().writeAndFlush(msg));
}
So lets imagine situation when some clients are publishing messages (e.g. "msg1", "abc2") in the same moment. Does it lead to concurrent problems? For example can I retrieve in some cases "msabg1c2" instead of "msg1abc2"? Or Netty takes care of such cases?
回答1:
Channel is thread-safe so no you should not have any problems as long as the calling order is correct
来源:https://stackoverflow.com/questions/50907416/netty-concurrent-writeandflush