Q11. What is a Race Condition?

Ans : When multiple thread execute Critical section of code segment, and thread execution order can lead to different results can be considered as a Race Condition. Lets assume we have below code segment

Class HadoopExam 

{

Int counter=0;

 

Int foo(){

return counter= counter+1; //Critical Section

}

}

 

Now there are two threads ThreadA and ThreadB. Both are executing above code. ThreadA read value of counter (which is 0 as of now) and will be updating it by one. However, as soon as ThreadA reads counter value as 0, at the same time ThreadB also read counter value which is also 0 (because ThreadA has not written back). Now finally when ThreadA and ThreadB both writes the Value. It will become 1 instead of 2 . Which is a wrong results, because counter is increased twice from 0 and result is still 1. This can be avoided by executing thread in proper order. This problem is known as a Race Condition. Race condition occurs only when Thread update the resource values, only reading will not create Race condition.

Q12.  How can you avoid Race Condition?

Ans: As we can see in above example “counter=counter+1” is not an Atomic operation. To avoid Race condition we need to make operation atomic. This can be done using Synchronized block or method. So only one thread at a time can execute Critical Section of the code. Hence, ThreadA is executing “counter=counter+1” then ThreadB has to wait.

Q13. What is the Impact of Synchronizing “Critical Section” of code?

Ans: In above example we have two threads ThreadA and ThreadB, and by Synchronizing we are allowing only one thread to execute and other ThreadB needs to wait, which will impact the overall performance of multithreaded application. Hence, it is always advisable to break critical sections in multiple part and synchronized accordingly. So it will not impact overall throughput of multithreaded application.

If Critical Section of code is larger than, we have to be very careful while breaking multiple Synchronized block, else it could lead another problem

Q14.  What do you mean by Thread Safe code?

Ans : Code which does not have any side effect , if multiple thread calls same code in different order is called Thread safe code. And code must not have any Race Condition, Deadlock ans Starvation.

Q15. What is local variables and why they are Thread Safe?

Ans : Variables you defined in a method is called local variable. See below example

 

Int foo(){

Int localCounter=10;

return localCounter = localCounter +1; //Local Variable increment

}

 

In above code “localCounter” is a local variable.

Thread safe: Local primitive variable are always thread safe because, they are always stored as part of thread’s stack (And thread stack will never be shared across threads). So it is always used by one thread. Hence, it is thread safe in above code “localCounter” is created in thread stack and once thread is out of method block, this variable will be Garbage collected.