C # Implementation of the thread-safe Singleton mode in the database connection pool

Source: Internet
Author: User

This article introduces three thread security Modes

1, lock

2, mutex

3, methodimpl

 

Previously written MySQL database connection pool connectionpool. CS

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io; using system. threading; using MySQL. data. mysqlclient; using system. runtime. compilerservices; namespace queue. service. basic {public class connectionpool {private stack <mysqlconnection> pool; private const int pool_max_size = 20; private int current_size = 0; private string connstring = ""; // connection string private sysproperty; private const string sys_property = "config \ sysproperty. XML "; Private Static connectionpool connpool; private connectionpool () {If (pool = NULL) {pool = new stack <mysqlconnection> () ;}} [methodimpl (methodimploptions. synchronized)] public static connectionpool getinstance () {If (connpool = NULL) {connpool = new connectionpool () ;}return connpool;} public mysqlconnection getconnection () {mysqlconnection conn; lock (this) {If (pool. count = 0) {If (current_size <pool_max_size) {conn = createconnection (); current_size ++; // Add the conn to the pool. push (conn);} else {try {Monitor. wait (this);} catch (exception e) {console. writeline (E. message) ;}}conn = (mysqlconnection) pool. pop ();} return conn;} private string getconnstring () {If (connstring = "") {sysproperty = new sysproperty (). loadproperty (path. combine (sys_property); string IP = sysproperty. getpropertyvalue ("databaseip"); string dbname = sysproperty. getpropertyvalue ("databasename"); string userid = sysproperty. getpropertyvalue ("databaseuser"); string userpwd = sysproperty. getpropertyvalue ("databasepassword"); connstring = "database =" + dbname + "; Data Source =" + IP + "; user id =" + userid + "; password = "+ userpwd +"; "+" pooling = true; charset = utf8; Port = 3306; ";} return connstring;} public void releaseconnection (mysqlconnection conn) {lock (this) {pool. push (conn); monitor. pulse (this) ;}} private mysqlconnection createconnection () {lock (this) {mysqlconnection newconn = new mysqlconnection (getconnstring (); newconn. open (); Return newconn ;}}}}

Summary:

1. The lock method is used in the above class.

Lock () is a mutex lock applied to an object. Only one thread is allowed to access the statement block in the braces after the lock (). It is unlocked after the code of the statement block is executed, other threads are allowed to execute their statement blocks only after unlocking.

2. The Singleton mode uses the lazy mode.

The hungry Chinese Style directly obtains the instance of this class when loading the class. It can be said that it is bound in the early stage; the lazy style is bound in the later stage, and the connpool is empty when loading the class, it is created only once when necessary. The hungry Chinese style is fast and efficient, but consumes system resources. The Lazy Chinese style is opposite. The lazy style still has a problem, that is, the late binding cannot ensure that the object can only be instantiated once. This requires that one mutex lock be set for the flag indicating whether the class is instantiated, and only one thread is allowed to access the object. This ensures that the object is instantiated only once.

3. methodimpl is used for thread security in singleton mode.

The getinstance () method can only be used by one thread at the same time.

4. Use the mutex class for synchronization

Modify the code:

private static Mutex mutex = new Mutex();        public static ConnectionPool getInstance()        {            mutex.WaitOne();            if (connPool == null)            {                connPool = new ConnectionPool();            }            mutex.ReleaseMutex();            return connPool;        }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.