title: Java - Semaphore release without acquire
body: <p>I have threads which are given random number (1 to n) and are instructed to print them in sorted order. I used semaphore such that I acquire the number of permits = random number and release one permit more than what was acquired.</p>
  
  <blockquote>
    <p>acquired = random number; released = 1+random number</p>
  </blockquote>
  
  <p>Initial permit count for semaphore is 1. So thread with random number 1 should get permit and then 2 and so on.</p>
  
  <p>This is supported as per the documentation given below </p>
  
  <blockquote>
    <p>There is no requirement that a thread that releases a permit must have acquired that permit by calling acquire().</p>
  </blockquote>
  
  <p>The problem is my program gets stuck after 1 for n>2.</p>
  
  <p>My program is given below:</p>
  
  <pre><code>import java.util.concurrent.Semaphore;
  
  public class MultiThreading {
      public static void main(String[] args) {
          Semaphore sem = new Semaphore(1,false);
          for(int i=5;i&gt;=1;i--)
              new MyThread(i, sem);
      }
  }
  class MyThread implements Runnable {
      int var;Semaphore sem;
      public MyThread(int a, Semaphore s) {
          var =a;sem=s;
          new Thread(this).start();
      }
      @Override
      public void run() {
          System.out.println("Acquiring lock -- "+var);
          try {
              sem.acquire(var);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
  
          System.out.println(var);
  
          System.out.println("Releasing lock -- "+var);
          sem.release(var+1);
      }
  }
  </code></pre>
  
  <p>Output is :<br/></p>
  
  <blockquote>
    <p>Acquiring lock -- 4<br/>
    Acquiring lock -- 5<br/>
    Acquiring lock -- 3<br/>
    Acquiring lock -- 2<br/>
    Acquiring lock -- 1<br/>
    1<br/>
    Releasing lock -- 1<br/></p>
  </blockquote>
  
  <p>While If I modify my code with tryAcquire, it runs perfectly well. 
  Below is new run implementation</p>
  
  <pre><code>@Override
  public void run() {
      boolean acquired = false;
      while(!acquired) {
          acquired = sem.tryAcquire(var);
      }
      System.out.println(var);
      sem.release(var+1);
  }
  </code></pre>
  
  <p>Can someone please explain the semaphore's permit acquire mechanism when mulitple threads are waiting with different permit request??</p>