Netty, concurrent writeAndFlush

会有一股神秘感。 提交于 2021-01-29 12:31:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!