Search code examples
javamultithreadingthread-safetynio

Java NIO: how to protect global data effectively?


Is there any difference in the ways we protect resources in thread-per-connection model and NIO-model (using Netty for example)? For example, if we have some global object the most obvious thing to make it's methods thread-safe is to make them syncronized.

Should we use the same approach when working with NIO-based communication? As I understand, the thread in NIO is more valuable resource than in thread-per-connection. If several threads will be blocked waiting for a synchronized resource to be released, can this have any impact on the performance of processing other requests, unrelated to this resource? If this is implementation-specific, how things work in Netty specifically?


Solution

  • Implementing thread safety is the same for NIO as any other thread pool. (Unless there is only one thread ;)

    Whether you have a small number or a large number of threads (mostly idle) hot resources will delay your processing. The problem is basically the same.

    You process tasks not resources. A hot resources can delay the tasks which use that resources but not tasks which do not depend on them.