Q46. Why we should avoid wait() or getting lock on a Constant strings or global objects?

Ans : We should avoid Constant String, because JVM internally store different Constant String with same value as a Single object.

String str1=new String(“HadoopExam.com”);

String str2=new String(“HadoopExam.com”);

 

JVM internally stored both the str1 and str2 as two separate reference variable pointing to single objects in String constant pool. Hence, if two different threads are working on two different object references can get a wrong/false signal.

Same problem occurs with globally shared objects.

Q47. What is Thread deadlock?

Ans: Deadlock is situation, when two or more threads are blocked and waiting to get lock on objects. Lets assume there are two threads ThreadA and ThreadB and there two shared objects obj1 and obj2. ThreadA is holding a lock on obj1 and also needs lock on obj2 to proceed further. Similarly ThreadB is holding lock on obj2 and needs lock on obj1 to proceed further. Now both ThreadA and ThreadB is waiting for each other to release the lock and no one can proceed further. This situation is called deadlock.

Q48. Why deadlock happens?

Ans: Deadlock occurs because two or more threads are waiting for each other locks at the same time. However, order of getting and releasing lock is not proper it can arise deadlock.

Q49. How can deadlock be prevented?

Ans: to prevent deadlock following techniques can be used

  • Lock Ordering: Locks needs to be taken and released in same order by each thread
  • Lock Timeout and retry: Threads which are waiting to get lock on threads does not get locks in specified time limit. Then it should release all the locks it has taken needs to re-try after sometime.
  • Deadlock Detection: Detect the deadlock and try to avoid. You can use thread priority as well to avoid deadlock.

Q50. What is thread starvation and what causes it?

Ans: Starvation means thread is waiting for infinite time or for longer periods because of it is not getting lock or CPU time. Following are the reasons for thread starvation

  1. Lower priority thread will never get a chance, because higher priority threads always exists in application.
  2. Thread is waiting for indefinitely, because it is not able to get lock on thread.