FileDocCategorySizeDatePackage
BusyFlag.javaAPI DocExample1476Tue Jan 28 17:14:12 GMT 1997None

BusyFlag.java

// This example is from the book _Java Threads_ by Scott Oaks and Henry Wong. 
// Written by Scott Oaks and Henry Wong.
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.

// Sample BusyFlag -- Chapter 4, p. 74.  This is the fully functional
// BusyFlag class.

public class BusyFlag {
     private Thread busyflag = null;
     private int busycount = 0;

     public synchronized void getBusyFlag() {
          while (tryGetBusyFlag() == false) {
               try {
                    wait();
               } catch (Exception e) {}
          }
     }

     public synchronized boolean tryGetBusyFlag() {
          if (busyflag == null) {
               busyflag = Thread.currentThread();
               busycount = 1;
               return true;
          }
          if (busyflag == Thread.currentThread()) {
               busycount++;
               return true;
          }
          return false;
     }

     public synchronized void freeBusyFlag() {
          if (getBusyFlagOwner() == Thread.currentThread()) {
               busycount--;
               if (busycount == 0) {
                    busyflag = null;
                    notify();
               }
          }
     }

     public synchronized Thread getBusyFlagOwner() {
          return busyflag;
     }
}