5 Replies Latest reply: Nov 14, 2012 7:00 PM by jtahlborn RSS

    Query regarding Semaphores. - Kindly advise.

    AjayL
      Helllo,

      I am inspecting a 3rd party code with Semaphore(0)
      On executing the code,the application runs but does not terminate.
      But if I change the Semaphore count to 1, the application starts and terminates.

      Can anyone please explain
      a) why does the application not terminate using Semaphore(0)?
      b) Does using Semaphore(0) make a thread block only to be terminated forcefully?

      Thanks,

      public class MyBackground{
      
          Thread thread;
      
          public MyBackground(String[] arguments) {
           }
      
          @Override
          public void initialise() {
              thread = new KeepMeAlive();
              thread.start();
          }
      
          // Using a static inner class
          private static class KeepMeAlive extends Thread {
              Semaphore lock = new Semaphore(0);
             
              public void run() {
                  Runtime.getRuntime().addShutdownHook(new Thread() {
                      @Override
                      public void run() {
                          lock.release();
                      }
                  });
                  lock.acquireUninterruptibly();
              }
          }
      }
      
      
      class Test {
           public static void main(String[] args){
                MyBackground mB = new MyBackground (new String[]{"Testing"});
                mB.initialise();
           }
           
      }