One DAO per thread or threadsafe DAO?

倾然丶 夕夏残阳落幕 提交于 2019-12-09 06:27:37

问题


I'm wondering if there's an approved practice in a multi-threaded app. Should I have one DAO per thread or simply make one DAO a thread safe singleton.


回答1:


This really depends a lot on the mechanism you're using for data access. If you have a very scalable data access, and lots of threads, using some form of thread static data access can be advantageous.

If you don't have scalable data access, your provider doesn't support multiple threads per process, or you just don't need the scalability at that point, using a singleton with appropriate synchronization is simpler and easier to implement.

For most business style applications, I personally think the singleton approach is easier to maintain, and probably better - if for no other reason than it's much, much easier to test effectively. Having multiple threads for data access is likely not required, as the data access is probably not going to be a bottleneck that effects usability (if you design correctly, and batch requests appropriately).




回答2:


Use the approach that best suits your application architecture, unless:

1) Your data access objects are expensive to create, in which case you should lean toward a thread-safe singleton.

2) Your objects maintain mutable state, as in the Active Record pattern. (Immutable DAO configuration state, like timeout thresholds, doesn't count.)



来源:https://stackoverflow.com/questions/2001073/one-dao-per-thread-or-threadsafe-dao

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!