title: Java Multithreaded Transactional service layer
body: <p>I have a task in which I have to implement a transactional service layer which manages multiple DAOs (those DAOs have only CRUD operations). In order to insert something into the database I have to use multiple DAOs, so I need to start a transaction.</p>
  
  <p>I implemented a DAOManager class which implements the singleton pattern. This class has methods like getNewsDAO() which return only an instance of a DAO. Basically I can say that the DAOManager and all the DAO classes have a single instance per program.</p>
  
  <p>I also implemented a ConnectionManager class which has 2 fields - a connection pool (used for retrieving a connection) and also a Connection field.</p>
  
  <p>Basically, when I call a service layer method the flow is something like:</p>
  
  <ul>
  <li>get the connection from the connection pool and set it to the connection field inside the connection manager</li>
  <li>call all dao methods and pass them the connection field from the ConnectionManager by a method parameter</li>
  </ul>
  
  <p>Every service class has a DAOManager field - which is singleton and a ConnectionManager field - the ConnectionManager is not a singleton. It has an instance per service class instance.</p>
  
  <p>The problem comes when multiple threads use service classes. 
  <strong>A transaction is made by a single thread</strong>  but I have to make sure that the same connection is not shared among threads.</p>
  
  <p>Should I move the DAOManager and ConnectionManager in a thread local and make the ConnectionManager also singleton? Basically a single instance of DAOManager and ConenctionManager per thread and change from passing the connection to a method in DAO to setting it in an instance field of a DAO?</p>
  
  <p>Or is my design already good practice?</p>