2

Generally a lot of applications these days use Spring which takes care of the life cycle of the pojo classes in their application. But what if my application cannot use Spring due to some other issues. How do I go from the Service layer of the application to the DAO layer.

Currently this is what I am doing.

public class MyServiceImpl{

    private static MyDAO daoInstance=new MyDAO();

    public void someMethod(){
        daoInstance.methodToCall();
    }

}

public class MyDAO{

   public void methodToCall(){


   }

}

Keeping the daoInstance in MyServiceImpl as static makes sure that there is only one instance across all ServiceImpl objects. But wouldn't this create concurrency issues if a lot of users access the same piece of code at the same time.

However if I don't keep it static, there would be one daoInstance with each MyServiceImpl object. Wouldn't this leave so many objects in the heap. How would the life cycle of these objects get managed.

I want to understand what is the correct way of navigating from one layer of the application to other layer keeping concurrency, performance and other such factors in mind.

Thanks for any help.

Arunabh
  • 167
  • 1
  • 7
  • 18

3 Answers3

2

First of all, Service class should not directly call DAO instance.

Interaction between service and DAO should always be through interface in order to make it loosely coupled.

You can create DAO instance as singleton in service class and is thread safe (i.e spring framework uses singleton by default) make sure that the global variables are not used in DAO.

If you make DAO object as singleton then the amount of objects created would be very less which in turn improves the performance.

prasanna
  • 21
  • 1
0

It depends on your requirement and design.

Do you want to control the resources? then make sure every one acquires them from one location aka singleton.

Do you worry about performance? then make sure you consider all factors including number of threads (concurrent access), I/O, memory usage with in object etc...

It is very tough to balance all non-functional requirements, but ideally while designing the application you have to make trade-off based on requirements and your business objectives.

For more information refer Non-Functional Requirements.

K139
  • 3,654
  • 13
  • 17
  • In case daoInstance is static and assuming that there are multiple users accessing the same someMethod() in a web application. Would the behavior be predictable (thread safe)? – Arunabh Jul 25 '17 at 19:31
0

Making DAO instance static will have nothing to do with multy threading. Even if you declared it as instance variable of MyServiceImpl you can still have multiple threads accessing the MyDAO.

I would still declare your MyDAO as instance variable since it will take very little space in memory. The DAO should not have much if any at all instance state. This should also make sure that it will be threads safe as well.

tsolakp
  • 5,858
  • 1
  • 22
  • 28