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.
As pointed out in comment. Deadlock happens when the below 4 conditions happens. Them being :
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