Thread Mutual Exclusive Section

Viewed 4301

Hello I just had phone interview I was not able to answer this question and would like to know the answer, I believe, its advisable to reach out for answers that you don't know. Please encourage me to understand the concept.

His question was:

"The synchronized block only allows one thread a time into the mutual exclusive section. When a thread exits the synchronized block, the synchronized block does not specify which of the waiting threads will be allowed next into the mutual exclusive section? Using synchronized and methods available in Object, can you implement first-come, first-serve mutual exclusive section? One that guarantees that threads are let into the mutual exclusive section in the order of arrival? "

 public class Test {
   public static final Object obj = new Object();

   public void doSomething() {
     synchronized (obj) {
          // mutual exclusive section
     }
   }
 }
5 Answers
Related