Tuesday, June 21, 2011

Mutual Exclusion among 2 different classes

Hello There!,

Recently I came across a very interesting problem, and the problem statement is as follows


There are 2 classes called A and B, with the methods - methodA() and methodB(). The class definition vaguely looks like this.

class A {


  public methodA() {
      statementA;
  }




}


class B {

    public methodB() {
         statementB;
   }
}

Now the 2 classes's methods contain a set of statements represented by statementA and statementB. Our goal here is to make these 2 statements in 2 different class, execute in a mutually exclusive manner. That means, when any thread executes statementA, none of the threads must be allowed to execute statementB. And when any thread executes statementB, none of the threads must be allowed to execcute statementA. Meanwhile, unlimited threads can simultaneously access statementA alone or statementB alone.


methodA and methodB can be changed in any form (making them synchronized or whatever). But method signatures are not allowed to be changed.




My Solution -

I thought of creating a new class - say Class C, which will have statementA and statementB, enclosed within 2 separates methods. These 2 methods will be static and synchronized.

class C {


   public static synchronized methodASync() {
         statementA;
   }




 public static synchronized methodBSync() {
         statementB;
   }


}

Now the call from methodA of Class A will be delegated to C.methodASync() and call from methodB of class B will be delegated to C.methodBSync().



class A {


  public methodA() {
      C.methodASync();

  }





}




class B {

    public methodB() {
         C.methodBSync();
   }
}


Since the methods in this class are static synchronized, any thread which executes any method of this class, first will try to acquire lock on this class and execute the methods. Now, when say thread1 executes methodASync none of the threads will be allowed to execute methodBSync or viceversa.

But there's one disadvantage. My problem says statementA; and statementB; should be executed in mutual exclusive manner, but it can allow multiple threads executing statementA at the same time. Since I am using Class level synchronization, even multiple calls to execute statementA/statementB happens synchronously.

Do you have a proper fail-safe solution?

















No comments:

Post a Comment