package com.dbxml.util;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: SimpleLockManager.java,v 1.2 2004/02/12 00:17:58 bradford Exp $
 */

import java.util.HashMap;
import java.util.Map;

/**
 * SimpleLockManager manages simple resource locks.  A resource is any shared
 * object.  Locks are exclusive in this model.
 *
 * @deprecated Only used by FSFiler for exclusive file locks
 */

public final class SimpleLockManager {
   private Map locks = new HashMap(); // Object to LockInfo

   public SimpleLockManager() {
   }

   /**
    * acquireLock acquires a lock on a resource.
    */
   public void acquireLock(long id) {
      acquireLock(new Long(id));
   }

   /**
    * acquireLock acquires a lock on a resource.
    */
   public void acquireLock(Object key) {
      LockInfo info;
      synchronized ( this ) {
         info = (LockInfo)locks.get(key);
         if ( info == null ) {
            info = new LockInfo();
            locks.put(key, info);
         }
      }
      synchronized ( info ) {
         if ( info.owner == Thread.currentThread() )
            return;

         while ( info.locked ) {
            try {
               info.wait();
            }
            catch ( Exception e ) {
            }
         }

         info.locked = true;
         info.owner = Thread.currentThread();
      }
   }

   /**
    * releaseLock releases a lock on a resource.
    */
   public void releaseLock(long id) {
      releaseLock(new Long(id));
   }

   /**
    * releaseLock releases a lock on a resource.
    */
   public void releaseLock(Object key) {
      LockInfo info;
      synchronized ( this ) {
         info = (LockInfo)locks.get(key);
      }
      if ( info == null )
         return;

      synchronized ( info ) {
         if ( info.owner != Thread.currentThread() )
            return;

         info.locked = false;
         info.owner = null;

         info.notify();

         synchronized ( this ) {
            if ( !info.locked && info.owner == null )
               locks.remove(key);
         }
      }
   }


   /**
    * LockInfo
    */

   private class LockInfo {
      public Thread owner;
      public boolean locked;
   }
}
