javamultithreadingdeadlockthread-synchronizationstarvation

Java Multi-threading Deadlock or Starvation?


I am learning for my OCP exam and are trying to understand when we are speaking of a thread deadlock or a thread is in starvation. in case of the scenario below I have doubt.

public class ThreadTest {

private static int i = 0;
    
public static void doSomething() {
synchronized(ThreadTest.class) {
    while(true) {
      System.out.println("count:" + ++i)
    } }
}

public static void main(String args[]) { 
New Thread(() -> doSomething()).start();
New Thread(() -> doSomething()).start();
}}

The first thread to acquires the lock of the synchronized ThreadTest class in doSomething() goes in a infinite loop never releasing the lock. The second thread keep waiting til the resource becomes available (what never happens).

Are we speaking of a Deadlock in this situation or Starvation? I think about Starvation because one thread is not getting access to a shared resource and for a deadlock threads block each others resources. But just to be sure i ask about it here.

Deadlock describes a situation where threads are blocked forever.

Starvation describes a situation where a thread is unable to gain regular access to shared resources.


Solution

  • As pointed out in comment. Deadlock happens when the below 4 conditions happens. Them being :

    1. Mutual Exclusion - B wants a resource A has. B cannot use the resource A is using(which is happening here).
    2. Hold and wait - A is holding a resource that B wants. A is also waiting for a resource to be freed that somebody else has(Not happening for A from the probem statement given)
    3. No Preemption - The resource A is holding cannot be snatched away from it by force(assuming that it is true here because not given other wise).
    4. Circular Wait - A is holding a resouce B wants. B is holding a resource A wants(Not happening here).

    Hence we see here that all the conditions are not met. So a deadlock cannot exist in this situation.

    There is however an infinite loop due to which A never gives up the lock. Hence B will be starved.

    This should clear your doubt. Cheers