Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Can we use DAO as a Singleton instance

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?
like image 643
Pawan Avatar asked Sep 25 '12 09:09

Pawan


People also ask

How can we maintain singleton in distributed environment?

The simplest approaches are: Add an expiry timer to your singleton cache so that every so often the cache gets purged and subsquent calls fetch the updated data from source (e.g. a database) Implement a notification mechanism for the cache using something like a JMS topic/tibRV.

Should DAO methods be static?

This way you can avoid concurrency issues. The disadvantage here is every time you call the static method, an instance to DataAccessor is created. Daos in most cases are stateless.In those cases I see no point in having non static methods in Daos, because we need to create an instance of that dao to access its method.

When we should not use Singleton pattern?

One rather bad thing about singletons is that you can't extend them very easily. You basically have to build in some kind of decorator pattern or some such thing if you want to change their behavior.

Can singleton have multiple instances?

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.


1 Answers

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

like image 190
jmj Avatar answered Sep 28 '22 01:09

jmj