Hibernate Session Management on

On the Blog: http://blog.csdn.net/jhxck/
Session management options in the various, ThreadLocal pattern has been widely used. ThreadLocal is a Java thread in a more specific binding mechanism. ThreadLocal access through the data is always associated with the current thread, that is, JVM for each running thread, binding the local instance of the access of private space, which often appear as multi-threaded environment, concurrent access issues a a kind of isolation mechanism. First, we need to know, SessionFactory responsible for creating Session, SessionFactory is a thread-safe, multiple concurrent threads can simultaneously access an instance of SessionFactory and obtain Session. And
Session is not thread-safe, that is, if multiple threads simultaneously using a Session instance data access,
Session data access is the logical result will be chaos. The following is a typical Servlet, we are trying to achieve through a class variable Session session reuse, in order to avoid to be re-created for each operation:
public class TestServlet extends HttpServlet (
private Session session;
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException (
session = getSession ();
doSomething ();
session.flush ();
)
public void doSomething () (
......// Access operation based on session
)
)
Code looks correct, even when we single test might not happen, but this generation of
Hibernate Developer's Guide Version 1.0
September 2, 2004 So many open source projects. Why not Open your Documents?
Once the compiled code to deploy to the actual operating environment, the incoming inexplicable errors are likely to make us feel not looking for head.
What is wrong?
First of all, Servlet running a multi-threaded, while the application server and not for each thread to create a Servlet
Instance, that is, TestServlet in only one instance of the application server (Tomcat in this is the case in other application servers may have different implementations), and this instance would be invoked as many concurrent threads, doGet method will also be different thread repeatedly calls can imagine, each call to doGet method, the only instance TestServlet
session variables are reset, the thread A running process, the other thread was, if implemented, then the session
Reference will change again after the thread A called session, the session may time before its use
session is no longer the same, obviously, the error also unexpected.
ThreadLocal appearance, making the problem solved.
Our example above, some minor modifications:
public class TestServlet extends HttpServlet (
private ThreadLocal localSession = new ThreadLocal ();
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException (
localSession.set (getSession ());
doSomething ();
session.flush ();
)
public void doSomething () (
Session session = (Session) localSession.get ();
......// Access operation based on session
)
)
You can see, localSession a ThreadLocal object of type, in the doGet method, we adopted the method to obtain the session set examples preserved in the doSomething method, get way out through the session instance.
This is the ThreadLocal is unique, it will for each thread maintains a private variable space. In fact,
The implementation principle is maintaining a JVM in the Map, the Map's key is that the current thread object, the value is the thread through the method of preservation of the object instance ThreadLocal.set. When the thread calls ThreadLocal.get method,
ThreadLocal object based on a reference to the current thread, remove the Map corresponding object to return.
This, ThreadLocal object through a reference to each thread as a distinction between the different threads of variables to isolate.

Hibernate example of official development manual provides a safeguard through the ThreadLocal Session of the good example:

public class HibernateUtil (
private static SessionFactory sessionFactory;
static (
try (
/ / Create the SessionFactory
sessionFactory = new
Configuration (). Configure (). BuildSessionFactory ();
) Catch (HibernateException ex) (
throw new RuntimeException (
"Configuration problem:" + ex.getMessage (),
ex
);
)
)
public static final ThreadLocal session = new ThreadLocal ();
public static Session currentSession () throws HibernateException
(
Session s = (Session) session.get ();
/ / Open a new Session, if this Thread has none yet
if (s == null) (
s = sessionFactory.openSession ();
session.set (s);
)
return s;
)
public static void closeSession () throws HibernateException (
Session s = (Session) session.get ();
session.set (null);
if (s! = null)
s.close ();
)
)
In the code, as long as the use of the above tools for the Session instance, we can achieve within the thread
Session sharing, in order to avoid frequent in the thread creation and destruction of Session instance. But note that the end of the thread closed Session.

It is also worth mentioning that the new version of the Hibernate Session when dealing with lazy loading mechanism has been built, only the database operations happen in real time, will be from the database connection pool for database connection, we need not worry too much about Session of sharing will lead to the thread life cycle database connection is continued occupation.

The Web program, we can make use of the new specification introduced Servlet2.3 Filter mechanism, easy life-cycle thread
Session management (on the Filter specific description, please refer to Servlet2.3 specification).
Filter runs through the life cycle of their coverage Servlet (JSP can also be seen as a special Servlet)
And the underlying object. Called before the Servlet Filter implementation, after the end of the call in the Servlet. Therefore,
Session for the Filter in the management process as it becomes ripe for Web. The following is a Filter for Session management through a typical case:
public class PersistenceFilter implements Filter
(
protected static ThreadLocal hibernateHolder = new ThreadLocal ();
public void doFilter (ServletRequest request, ServletResponse
response, FilterChain chain)
throws IOException, ServletException
(
hibernateHolder.set (getSession ());
try
(
......
chain.doFilter (request, response);
......
)
finally
(
Session sess = (Session) hibernateHolder.get ();
if (sess! = null)
(
hibernateHolder.set (null);
try
(
sess.close ();
)
catch (HibernateException ex) (
throw new ServletException (ex);
)
)
)
)
......
Hibernate Developer's Guide Version 1.0
September 2, 2004 So many open source projects. Why not Open your Documents?
)
DoFilter get by on and off Session, and in the period running all objects (Filter chain, the rest of the Filter, and cover the Servlet and other objects) to reuse an instance of this Session, to ensure a
Http Request processing takes a Session, improve overall performance.
In the actual design, Session reuse achieve thread-level general enough in an attempt to achieve through the HttpSession Session user level reuse but may cause other problems. Everything can not be too far, Session reuse the same.

On the Blog: http://blog.csdn.net/jhxck/

分类:Java 时间:2010-03-29 人气:346
分享到:
blog comments powered by Disqus

相关文章

  • Ten Steps to optimize SQL Server Data Access 2011-08-24

    The story begins: You and your team through unremitting efforts, and finally make the site successful on-line, at the beginning, fewer registered users, site performance is good, but with the increase in registered users, access speeds began to slow,

  • Creating a MySQL data source using WebSphere Application Server 2010-03-29

    DATABASE CONNECTIVITY Recently, Senior Technical Editor Dan Velasco wrote an article on how to connect to the popular open source database MySQL from WebSphere Studio Application Developer (see http://www.webspherepower.com/issues/issue200310/0000111

  • Java Web Application Server Comparison 2010-12-30

    Transfer from: http://special.e800.com.cn/070902/ Case] [Editor Tomcat is an open source, run servlet and JSP Web application software application software based on Java Web container. Subprojects by the Apache-Jakarta Tomcat support from the open so

  • Window under the WebSphere Application Server 7 installation 2011-08-17

    Window under the WebSphere Application Server 7 installation First, install the WebSphere Application Server 7 1, click WebSphere Application Server installation program launchpad.exe, pop-up installation Welcome window, click Start WebSphere Applica

  • [Change] Eclipse Remote Debugging WebSphere Application Server (WAS) 2008-11-21

    We use Eclipse Developer Web project, many will use a plug-in (for example, MyEclipse) to the application on the Tomcat single-step debugging. WAS have to debug the application, under, MyEclipse is also possible, but in the MyEclipse to start WAS slo

  • Case Study: Tuning WebSphere Application Server V7 Performance 2010-03-29

    From DW China Introduction IBM WebSphere Application Server is a reliable enterprise-class application server, which provides a set of core components, resources and services for developers to use in your application. Every application has unique nee

  • WebSphere Application Server memory leak detection and diagnostic tools 2010-11-25

    Level: Intermediate School North Lee (lixuec@cn.ibm.com), Senior Software Engineer, IBM China Software Development Center November 21, 2006 This article describes how to implement WebSphere Application Server application memory leak detection, and IB

  • web server.application server.http server differences 2011-04-15

    web server, application server, http server differences Web server's basic function is to provide Web information browsing services. It only supports the HTTP protocol, HTML document format and URL. With the client's Web browser with. Because the mai

  • WEB server and application server What is the difference? 2010-03-29

    Popular speaking, Web server, send (serves) so that browsers can view the page, but the application server provides the client application can call (call) the method (methods). To the point, you can say: Web server dedicated to handling HTTP requests

  • oracle blob data access 2010-06-16

    Oracle's lob (Large Object) can store very large of data (probably yes 4GB), so you can File or by any other object sequence into bytes Output stream (OutputStream) after the written to the database Zhihoushiyong bytes Shuru stream (InputStream) to r

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 1.017 (s). 12 q(s)