6

This is a general question, not specific to my current application.

In a heavy Traffic MultiThreaded application, what is the approach to do following: assume that there is a DAO which contains a method updateData to update some data inside of a database.

Questions:

  1. Is it a good approach to have a Singleton instance of that DAO class and access it's method updateData?
  2. Or should I every time create a new object of that DAO and call the method updateData?
rand0rn
  • 678
  • 2
  • 12
  • 29
Pawan
  • 31,545
  • 102
  • 256
  • 434

3 Answers3

6

Yes it is definitely good idea to create a singleton for such services, make sure it doesn't have any state related issue when accessed by multiple threads

I would have marked such DAOs as Spring beans

jmj
  • 237,923
  • 42
  • 401
  • 438
  • Thanks a lot , in our case our DAO class has got state (an Instance Variable ) so i guess they are creating a new Object every time of that DAO . – Pawan Sep 25 '12 at 09:31
  • depends, if that instance can be shared with multiple threads then no need of that (for quick example logger), if that member variable has something to do with state of DAO (which is generally not a case) then you should go with 2 – jmj Sep 25 '12 at 09:34
  • 4
    a DAO can have member variables but that doesn't mean they have a "state". Just ensure that the value of those variables doesn't change between invocations of the DAO methods and that invoking a single method twice with same input params returns the same value. – Alonso Dominguez Sep 25 '12 at 09:35
5

It is better to create a single instance of your DAO and pass it into the constructor of classes that need it. I tend to avoid singletons whenever I can, because amongst other things, they make your code difficult to test and hide dependencies.

Take a look at the answers on this question: What is so bad about Singletons?

Community
  • 1
  • 1
dogbane
  • 266,786
  • 75
  • 396
  • 414
4

You can have a singleton instance of your DAO, you only have to make sure that the DAO is stateless, but DAOs should be stateless anyway.

phlogratos
  • 13,234
  • 1
  • 32
  • 37