Netty - can I cache those ChannelHandlerContext in

2019-05-21 18:37发布

问题:

Here is the step of implementation and questions:

  1. Netty server handler receives message from client

  2. Because there are other running threads to process the user data, we need to put this request to a queue and let the worker process

  3. After the worker process the data, can we response back to client in the worker thread? i.e. either using a HashMap to cache the ChannelHandlerContext and get it later from worker thread to response?

Thank you all

回答1:

Yes, you can. The operations provided by ChannelHandlerContext are all thread-safe, and thus you can keep the context instance for later use and use it from other thread.

A ChannelHandlerContext has the same life cycle with the Channel it belongs to. When the Channel is closed, ChannelHandlerContext is also dereferenced from the pipeline. If you keep the reference to a ChannelHandlerContext, you should dereference it or make sure the garbage collector can reclaim it.