DatabaseConnectionPool.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* -*- C++ -*- */
  2. /****************************************************************************
  3. ** Copyright (c) 2001-2014
  4. **
  5. ** This file is part of the QuickFIX FIX Engine
  6. **
  7. ** This file may be distributed under the terms of the quickfixengine.org
  8. ** license as defined by quickfixengine.org and appearing in the file
  9. ** LICENSE included in the packaging of this file.
  10. **
  11. ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
  12. ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  13. **
  14. ** See http://www.quickfixengine.org/LICENSE for licensing information.
  15. **
  16. ** Contact ask@quickfixengine.org if any conditions of this licensing are
  17. ** not clear to you.
  18. **
  19. ****************************************************************************/
  20. #ifndef FIX_DATABASECONNECTIONPOOL_H
  21. #define FIX_DATABASECONNECTIONPOOL_H
  22. #ifdef _MSC_VER
  23. #pragma warning( disable : 4503 4355 4786 4290 )
  24. #endif
  25. #include "DatabaseConnectionID.h"
  26. #include <string>
  27. #include <map>
  28. namespace FIX
  29. {
  30. template< typename T > class DatabaseConnectionPool
  31. {
  32. public:
  33. DatabaseConnectionPool( bool poolConnections )
  34. : m_poolConnections( poolConnections ) {}
  35. T* create( const DatabaseConnectionID& id )
  36. {
  37. if( !m_poolConnections )
  38. return new T( id );
  39. if( m_connections.find( id ) == m_connections.end() )
  40. {
  41. m_connections[id] = Connection
  42. ( new T(id), 0 );
  43. }
  44. m_connections[id].second++;
  45. return m_connections[id].first;
  46. }
  47. bool destroy( T* pConnection )
  48. {
  49. if( !m_poolConnections )
  50. {
  51. delete pConnection;
  52. return true;
  53. }
  54. const DatabaseConnectionID& id = pConnection->connectionID();
  55. if( m_connections.find( id ) == m_connections.end() )
  56. return false;
  57. Connection& connection = m_connections[id];
  58. if( connection.first != pConnection )
  59. return false;
  60. connection.second--;
  61. if( connection.second == 0 )
  62. {
  63. m_connections.erase( id );
  64. delete pConnection;
  65. }
  66. return true;
  67. }
  68. private:
  69. typedef std::pair<T*, int>
  70. Connection;
  71. typedef std::map<DatabaseConnectionID, Connection>
  72. Connections;
  73. Connections m_connections;
  74. bool m_poolConnections;
  75. };
  76. }
  77. #endif