Hibernate put connection into threadlocal to implement database connection pooling

Source: Internet
Author: User
Tags connection pooling static class

Why ThreadLocal?

In any case, to write a multithreaded security (Thread-safe) program is difficult, in order to allow threads to share resources, must be careful to synchronize the shared resources, synchronization brings some performance delay, on the other hand, in the process of synchronization, but also pay attention to the object lock and release, to avoid the deadlock, Various factors make it difficult to write multi-threaded programming.

Try to think of the problem of multi-threaded shared resources from another perspective, since sharing resources is so difficult, then simply don't share, why not create a copy of a resource for each thread. Isolating the behavior of each thread accessing the data is done by giving each thread a specific space to keep the resources that the thread has exclusively

What is threadlocal?

As the name implies, it is local variable (thread local variable). Its function is very simple, that is, each thread that uses the variable provides a copy of the value of a variable, and each thread can independently change its own copy without conflicting with the other thread's copy. From a thread's point of view, it's as if every thread has exactly the variable.

Usage Scenarios

    1. To keep state with a thread (User-id, Transaction-id, Logging-id)
    2. to the cache objects which you need frequently

Threadlocal class implements thread-scoped shared variables

It consists of four methods consisting of InitialValue (), Get (), set (T), remove (), which is notable for InitialValue (), which is a protected method, apparently implemented specifically for subclass rewriting. This method returns the initial value of the current thread's local variable, which is a deferred call method that executes only 1 times when a thread calls get () or set (Object) for the 1th time. The true implementation in threadlocal returns a null directly:

The principle of threadlocal

How does threadlocal maintain a copy of a variable for each thread? In fact, the idea of implementation is simple, there is a map in the Threadlocal class that stores a copy of each thread's variable. For example, the following implementation:

public class ThreadLocal
{
Private MAP values = Collections.synchronizedmap (new HashMap ());
Public Object Get ()
{
Thread curthread = Thread.CurrentThread ();
Object o = values.get (curthread);
if (o = = null &&!values.containskey (curthread))
{
o = InitialValue ();
Values.put (Curthread, O);
}
return o;
}

public void Set (Object newvalue)
{
Values.put (Thread.CurrentThread (), newvalue);
}

Public Object InitialValue ()
{
return null;
}
}

Use of ThreadLocal

Use method One:

Hibernate document when you see the section about making threadlocal manage multithreaded access. The specific code is as follows

1. public static final ThreadLocal session = new ThreadLocal ();
2. public static Session Currentsession () {
3. Session S = (session) Session.get ();
4.//open a new session,if this session has none
5. if (s = = null) {
6. S = sessionfactory.opensession ();
7. Session.set (s);
8.}
return s;
9.}

We analyze each line
1. Initializes a Threadlocal object, Threadlocal has three member methods get (), set (), InitialValue ().
If InitialValue is not initialized, InitialValue returns NULL.
3. The get of the Session returns its corresponding thread internal variables based on the current thread, which is the net.sf.hibernate.Session we need (equivalent to each database connection). It is not safe to share database links in multi-threaded situations. Threadlocal ensures that each thread has its own s (Database connection).
5. If this thread was first accessed, naturally, s (database connection) would be null, and then a session would be created, specifically row 6.
6. Create a database connection instance s
7. Save the database connection s to threadlocal.
8. If the current thread has accessed the database, get () from the session can get the connection instance that the thread last acquired.

Use Method Two

When you want to initialize a special value to a thread, you need to implement the subclass of the threadlocal and override the method, typically using an internal anonymous class to subclass the Threadlocal, which is how you create the JDBC connection context in Easydbo:

public class jdbccontext{
private static Logger Logger = Logger.getlogger (Jdbccontext.class);
Private DataSource DS;
protected Connection Connection;
Private Boolean isValid = true;
private static ThreadLocal Jdbccontext;

Private Jdbccontext (DataSource DS) {
This.ds = ds;
CreateConnection ();
}
public static Jdbccontext Getjdbccontext (Javax.sql.DataSource DS)
{
if (jdbccontext==null) jdbccontext=new jdbccontextthreadlocal (DS);
Jdbccontext context = (Jdbccontext) jdbccontext.get ();
if (context = = null) {
context = new Jdbccontext (DS);
}
return context;
}

private static class Jdbccontextthreadlocal extends ThreadLocal {
Public Javax.sql.DataSource DS;
Public jdbccontextthreadlocal (Javax.sql.DataSource DS)
{
This.ds=ds;
}
Protected synchronized Object InitialValue () {
return new Jdbccontext (DS);
}
}
}

Using singleton mode, different threads call Getjdbccontext () to get their own jdbccontext, all by jdbccontextthreadlocal the built-in subclasses to get the thread local variables of the Jdbccontext object

This article turns from http://blog.csdn.net/wenzhihui_2010/article/details/8985575 thanks to the author

Hibernate put connection into threadlocal to implement database connection pooling

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.