DEV Community

Piyush
Piyush

Posted on

Thread Congestion In Java

Thread Congestion can occur when two or more threads are trying to access the same, guarded data structure at the same time. "Guarded" mean that the data structure is guarded using synchronized blocks or a concurrent data structure so that the data structure is thread safe. The resulting thread congestion means that the threads trying to access the shared data structure are spending a high amount of time waiting in line to access the data structure - wasting valuable execution time on waiting.

Image description

Thread Blocking Data Structure May Cause Thread Congestion

A data structure which blocks threads from accessing it - depending on what other threads are currently accessing it, may cause thread congestion. If more than one thread accesses such a data structure at the same time, one or more of the threads may be queued up waiting to access the data structure. The queueing of threads is not visible in code. This queueing happens inside the JVM. Therefore thread congestion is not easy to spot simply by looking at the code. We need profiling tools to detect thread congestion.

A Blocked Thread Loses Execution Time

While a thread is blocked trying to execute a blocking data structure, it cannot do anything. While being blocked the thread loses possible execution time. The longer the thread is blocked, the more potential execution time it loses.

More Threads - Higher Congestion

The more the number of threads that attempts to access a shared data structure, the higher the risk of thread congestion.

Alleviating Thread Congestion

To lessen thread congestion we must reduce the number of threads trying to access the blocking data structure at the same time. There are several ways to reduce thread congestion namely:

  • Multiple Data Structures
  • Non-blocking Concurrency Algorithms
  1. Multiple Data Structures
    One way to alleviate thread congestion is to give each consuming thread its own queue, and have the producing thread distribute the objects among those data structures.

  2. Non-blocking Concurrency Algorithms
    Another way is to use "non-blocking concurrency algorithms" where the threads accessing the data structure are never blocked.

Top comments (0)