Thread security and thread insecurity in nhib.pdf

Source: Internet
Author: User

The basic feature of NHibernate is to map object-oriented programming languages to relational databases. In NHibernate, persistence Object PO (Persistent Object) is used to complete persistence operations, PO operations can only be synchronized to the database under Session management. However, the Session here does not refer to HttpSession and can be understood as based on ADO. NET Connnection. Session is the center of NHibernate operation. The object lifecycle, transaction management, and database access are closely related to the Session.


First, we need to know that SessionFactory is responsible for creating sessions. SessionFactory is thread-safe, and multiple concurrent threads can simultaneously access one SessionFactory and obtain Session instances from it. There is only one data storage source (database), and only one SessionFactory is a heavyweight Object. If the application only has one data storage source, only one SessionFactory instance needs to be created, the random creation of SessionFactory instances will occupy a large amount of memory space. Only one session is created here. Generally, the singleton mode is used to allow all requests in this application domain to access the same SessionFactory. However, the session of this instance is lightweight. The Session is not thread-safe. That is to say, if multiple threads use one Session instance for data access at the same time, the Session data access logic will be disordered. therefore, the created Session instance must run on the local access null so that it is always related to the current thread.


To ensure a browser access, that is, a request, all uses their respective sessions. In Java (Hibernate), ThreadLocal is a special thread binding mechanism in Java, data accessed through ThreadLocal is always related to the current thread. That is to say, JVM binds a private local instance access space for each running thread, this provides an isolation mechanism for concurrent access problems that often occur in multi-threaded environments. ThreadLocal is the local variable of the thread. That is to say, each thread that uses this variable must provide a copy for this variable. The value of this variable changed by each thread is only the value of this copy, the value of this variable does not affect other threads. ThreadLocal isolates data sharing among multiple threads and does not share resources among multiple threads. Therefore, thread synchronization is no longer required.

In C #, there is also a mechanism for local thread variables. You only need to set the Session lifecycle to thread_static in the NHibernate configuration file. This configuration is generally used when nhib.pdf is used in windows service. In Web applications, it is generally placed in requet. ASP. net mvc is usually used in combination with Controller. Generally, the service method of each domain is called in the controller to perform various database operations. Therefore, we only need, bind a new session to the current request. This Session is used for all database operations.

   [NHibernateSession]    public ActionResult SaveNewOrder(Order order)    {       ......       return RedirectToAction("Index");    }    [AttributeUsageAttribute(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]    public class NHibernateSessionAttribute : FilterAttribute, IActionFilter    {        public NHibernateSessionAttribute() : base()        {        }        public void OnActionExecuting(ActionExecutingContext filterContext)        {            var session = SessionProvider.GetNewSession();            CurrentSessionContext.Bind(session);        }        public void  OnActionExecuted(ActionExecutedContext filterContext)        {            CurrentSessionContext.Unbind(SessionProvider.GetSessionFactory()).Close();        }    }

In this way, through the idea of Aspect-oriented programming, the interception method is bound to a Session of the current request before each database operation, regardless of the number of methods in the data operation layer, for how many database operations, you only need to use the GetCurrentSession method to obtain the same Session. after the Action is completed, the Session will be closed and unbound. Note: During the Close operation, if no operation is submitted in the current Session, the operation will be flushed to the database. For example, we do not have this interception and close process in Windows Service. After completing the corresponding operation in the Session, pay attention to calling the Session. the Flush () method to synchronize data to the database. Otherwise, the database will not change.


One Session cannot be used in multiple threads (that is, in multiple requests), but multiple sessions may exist in one request. No performance error is returned, like ADO.. NET, two connections are created in a method to operate on the same database at the same time. Although there are performance problems, operations can still be implemented. NOTE: If Transaction processing is involved, it must be completed in the same Session. However, we generally do not use this method, instead of opening sessions multiple times in a request, because it does have performance problems and cannot use transactions.




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.