/*
 *  ZThreads, a platform-independant, multithreading and 
 *  synchroniation library
 *
 *  Copyright (C) 2000-2002, Eric Crahen, See LGPL.TXT for details
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *
 *  SUNY @ Buffalo, hereby disclaims all copyright interest in the
 *  ZThreads library written by Eric Crahen
 */

#ifndef __ZTSHAREDINSTANCE_H__
#define __ZTSHAREDINSTANCE_H__

#include "zthread/ZThread.h"
#include "zthread/Guard.h"
#include "zthread/Mutex.h"

namespace ZThread {
  
/**
 * @class SharedInstance
 *
 * @author Eric Crahen <crahen@cse.buffalo.edu>
 * @date <2002-02-24T09:29:18-0500>
 * @version 1.1.0
 *
 * This template creates a counted Singleton instance of type
 * SHARED. Its a combination of the handle-body idiom and a Singleton.
 * It will only delete the Singleton after all instances of it are 
 * out of scope. This is a bit more ideal than using a pattern like the
 * SingletonDestroyer for certain situations. The Singleton portion of this
 * pattern remains hidden from the user.
 *
 * The SingletonDestroyer, an alternative approach, makes no guarantee as to 
 * what order or when the Single is destroyed. This becomes problematic
 * when Singleton's refer to one another explicitly or implicitly through
 * shared data. The Singleton can be deleted in an inappropriate order
 * or at an unexpected time - freeing data still in use by another 
 * Singleton that has not been destroyed yet. This leads to access violations
 * and in some cases memory leaks.
 *
 * The ObjectLifetimeManager used in the ACE framework presents a much more
 * controlled and complex solution. However, for small, simple applications
 * that include co-dependent Singleton's, or short lived Singleton's this is a 
 * good solution.
 *
 *
 * @example This example demonstrates how to use this pattern to create a 
 * a single SocketPump object that will drive the low level i/o of a Socket
 * implementation in a separate thread. The details of the i/o are left out
 * for brevity.
 *
 *  class SocketImpl {
 *
 *    ...
 *    SharedInstance<SocketPump> _pump;
 *
 *  public:
 *    SocketImpl(...) { _pump.register(this); }
 *    virtual ~SocketImpl(...) { _pump.unregister(this); }
 *    ...
 *  };
 *
 *
 * The SocketPump going to refer to the same SharedInstance for all SocketImpl
 * objects. It will be destroyed when all the SocketImpl go out of scope. The
 * SocketPump is automatically created & started and stopped & destroyed as
 * necessary.
 *
 */
template <class SHARED>
class SharedInstance {
  
  SHARED* _pInstance;
  
public:
  
  /**
   * Update the shared instance count, instantiate the object if
   * necessary
   */
  SharedInstance() {
  _pInstance = instance();
  increment();
  
  };
  
  /**
   * Decrements the shared instance count, clean up the shared object
   * if the count drops to 0
   */
  ~SharedInstance() {
  decrement();
  };

  /**
   * Provide access to the shared instance
   *
   * @return SHARED* object instance being shared
   */
  SHARED* operator->() { return _pInstance; }

  /**
   * Provide access to the shared instance
   *
   * @return SHARED* object instance being shared
   */
  const SHARED* operator->() const { return _pInstance; }
  
private:
  
  // This instance method uses a Mutex and two
  // checks to minimize access to the Mutex which
  // could be slow - and to avoid deadlocks
  static SHARED* instance() {
  
  if(_Instance == (SHARED*)0) {
    
    Guard<Mutex> guard(_Mutex);
    if(_Instance == (SHARED*)0) {
    _Instance = new SHARED;
    }
    
  }
  
  return _Instance;
  
  };
  
  // Increment Instance count
  static int increment() {
  
  if(_Instance != (SHARED*)0) {
    
    Guard<Mutex> guard(_Mutex);
    if(_Instance != (SHARED*)0) {
    _pCount++;
    return _pCount;
    }
  }
  
  return -1;
  }
  
  static bool decrement() {
  
  if(_Instance != (SHARED*)0) {
    
    Guard<Mutex> guard(_Mutex);
    if(_Instance != (SHARED*)0) {
    
    if( --_pCount == 0 ) {
      
      delete _Instance;
      
      _Instance = (SHARED*)0;
      _pCount = 0;
      return true;
    }
    }
    
  } else { 
    // Should not be reached unless the pointer was externally
    // deleted
  }
  
  return false;
  }
  
private:
  static Mutex  _Mutex;
  static SHARED*  _Instance;
  static int _pCount;
};
  
template <class SHARED>
Mutex SharedInstance<SHARED>::_Mutex;
  
template <class SHARED>
SHARED* SharedInstance<SHARED>::_Instance = (SHARED*)0;
  
template <class SHARED>
int SharedInstance<SHARED>::_pCount = 0;
  
  
};

#endif
