title: Allow only one thread at the time to use an object
body: <p>I have the following class:</p>
  
  <pre><code>public class MyClass{
  
      private List&lt;Integer&gt; ints = new LinkedList&lt;Integer&gt;();
  
      public List&lt;Integer&gt; getInts(){
          return ints;
      }
  
      public synchronized void doAction(){ 
          //Do some with the list
      }
  }
  </code></pre>
  
  <p>I need to allow only one thread at the time having acces to the <code>List</code>. I would do that as follows:</p>
  
  <pre><code>public class MyClass{
  
      private List&lt;Integer&gt; ints = new LinkedList&lt;Integer&gt;();
      private static final Semaphore s = new Semaphore(1);
  
      public List&lt;Integer&gt; getInts(){
          s.acquire();
          return ints;
      }
  
      public void release(){
          s.release();
      }
  
      public synchronized void doAction(){ 
          s.acquire();
          //Do some with the list
          s.release();
      }
  }
  </code></pre>
  
  <p>But the implementaion is obviously not reliable, because if the client request the <code>List</code> through the getter for adding some elements into it and forget to call <code>release()</code> we'll get into troubles if try to invoke the <code>doAction</code> method. </p>
  
  <p>What is the solution for the problem?</p>