I was reading this post and came across the term ” thread starvation deadlock”. What is thread starvation dead lock?

  public class Demo {
    static ExecutorService threadPool = Executors.newFixedThreadPool(1);

    public static void doTask(int n, Runnable r) {
      Collection<Callable<Object>> c = new ArrayList<Callable<Object>>(n);
      for (int i = 0; i < n; i++) {
        c.add(Executors.callable(r));
      }

      try {
        threadPool.invokeAll(c);
      } catch (InterruptedException ie) {
      }
    }

    public static void main(String[] args) {
      final Runnable task1 = new Runnable() {
        public void run() {
          System.out.println(Thread.currentThread().getName());
        }

      };

      Runnable task2 = new Runnable() {

        public void run() {
          System.out.println(Thread.currentThread().getName());
          doTask(1, task1);
        }
      };
      doTask(1, task2);
    }
  }

doTask creates a collection of Callable objects and passes this collection to the thread pool which creates threads to execute these tasks. We are using a fixed thread pool of size 1. So, this thread pool can create a maximum of one thread to execute the tasks in the given collection. When we pass task2 to this thread pool, it creates a single thread and executes the given task. Now task2 internally again calls doTask giving it task1. Now, doTask submits task1 to the thread pool. But, the thread pool has only one thread and that thread is busy executing task2. Until task2 is completed, thread pool cannot execute task1 (because it cannot create more than one thread to execute the given tasks) and task2 will never complete until task1 is completed. Voila, deadlock due to thread starvation.

Advertisements