Ensuring only one thread is in a class
<p>I have a DAO class which has multiple methods which update DB tables. These methods are called in many different places throughout the codebase, in many different orders.</p>

<pre><code>public class Dao {
  public synchronized updateA()
  public synchronized updateB()
  public synchronized updateC()
  public synchronized getA()
  public synchronized getB()
  public synchronized getC()
}
</code></pre>

<p>I'm having an issue where Class1 wants to call <code>getA()</code>, <code>getB()</code>, and <code>getC()</code> in sequence. The three tables A, B, and C are related, so I need to get their state synchronized at one point in time. </p>

<p>However, after Class1 calls <code>getA()</code> and before it calls <code>getB()</code>, Class2 on another thread jumps in and calls <code>updateB()</code>, which breaks things.</p>

<p>Is it possible to lock the entire DAO class while any thread is in there, and only unlock it when it's finished?</p>

<p>I've tried putting a static ReentrantLock in the DAO class and locking it from Class1, but I'm not sure how to go from there.</p>

<p>I've gotten as far as the following:</p>

<pre><code>public class Class1 {
  public void check() {
    dao.daoLock.lock();
    dao.getA();
    dao.getB();
    dao.getC();
    dao.daoLock.unlock();
  }
}

public class Dao {
  public static final daoLock = new ReentrantLock();
  public synchronized updateA() {
    daoLock.lock();
    // Do stuff...
  }
  public synchronized updateB() {
    daoLock.lock();
    // Do stuff...
  }
  public synchronized updateC() {
    daoLock.lock();
    // Do stuff...
  }
  public synchronized getA() {
    daoLock.lock();
    // Do stuff...
  }
  public synchronized getB() {
    daoLock.lock();
    // Do stuff...
  }
  public synchronized getC() {
    daoLock.lock();
    // Do stuff...
  }
}
</code></pre>

<p>I'm unsure about the location of the unlock. If I put it in each the DAO class methods it's going to let other threads in isn't it?</p>

<p>Is there a better solution here?</p>