db连接应该是单连接吗? [英] should a db connection be a singleton?

查看:141
本文介绍了db连接应该是单连接吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中创建单例的最佳方法是什么?
DB连接是否为单例(单线程自动线程安全)?因为理论上数据库不能被许多用户同时访问。

解决方案

数据库连接通常不应该是



两个原因:


  1. 许多数据库驱动程序不是线程安全的。使用单例表示如果你有很多线程,它们将共享相同的连接。单身形式不会给你线程安全。它只是允许许多线程轻松地共享全局实例。

  2. 我个人认为,Singleton经常导致设计不好:看到这篇文章(由别人) http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/

而不是这样做考虑一个数据库池。游泳池是共享的(如果你想要的话可​​以是单身人士)。当你需要做数据库工作时,您的代码会这样做:

  getConnectioFromPool(); 

doWork()
closeConnection()//释放回池

示例池库:




What is the best way in Java to create a singleton? Should a DB connection be a singleton (being a singleton it's automatically thread-safe)? Because theoretical the DB can't be accessed by many users in the same time.

解决方案

A DB connection should not normally be a Singleton.

Two reasons:

  1. many DB drivers are not thread safe. Using a singleton means that if you have many threads, they will all share the same connection. The singleton pattern does not give you thread saftey. It merely allows many threads to easily share a "global" instance.
  2. Personally, I think Singleton often leads to bad design: See this post (by somebody else) http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/

Instead of doing this consider a database pool. The pool is shared (and could be a singleton if you wanted). When you need to do database work your code does this:

getConnectioFromPool();

doWork()
closeConnection() // releases back to pool

Sample Pool Libraries:

这篇关于db连接应该是单连接吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆