title: Blocking method calls on an object for a period of time
body: <p>I'm working on a multithreaded Java project where I would like to have objects that prevent their methods from being called from any thread for some period of time. Ideally, those method calls would not be thrown out, but simply queued up until the cooldown from the previous method has completed. Here's a simple example of a class with that kind of functionality:</p>
  
  <pre><code>public class A {
  
      private synchronized void cooldown(long ms) {
          long finishTime = ms + System.currentTimeMillis();
          while (System.currentTimeMillis() &lt; finishTime);
      }
  
      public synchronized void foo() {
          // foo's code
          cooldown(1000);
      }
  
      public synchronized void bar() {
          // bar's code
          cooldown(2000);
      }
  
  }
  </code></pre>
  
  <p>This works, but I'm expecting to have quite a few of the above objects and I feel like the loop inside of <code>cooldown()</code> is wasteful. I'd love to use a construct like <code>Thread.sleep()</code>, but in this case, that would have the undesirable effects of forcing the calling thread to sleep and not preventing any other thread from making method calls on <code>A</code>. Any suggestions?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>To clarify, given the following implementation:</p>
  
  <pre><code>public synchronized void foo() {
      System.out.println("foo");
      cooldown(1000);
  }
  
  public synchronized void bar() {
      System.out.println("bar");
      cooldown(2000);
  }
  
  public static void main(String[] args) {
      final A a = new A();
  
      new Thread(new Runnable() {
          public void run() {
              a.foo();
          }
      }).start();
  
      System.out.println("foobar");
  
      new Thread(new Runnable() {
          public void run() {
              a.bar();
          }
      }).start();
  }
  </code></pre>
  
  <p>I would like <strong>foo</strong> and <strong>foobar</strong> to print instantly (order doesn't matter), followed by <strong>bar</strong> a second later. If <code>cooldown()</code> just called <code>Thread.currentThread().sleep(ms)</code> instead of the current implementation, then <strong>foo</strong> would print instantly, followed by <strong>foobar</strong> and <strong>bar</strong> a second later. </p>