Java-ThreadLocal mode and OSIV mode (53), threadlocalosiv

Source: Internet
Author: User

Java-ThreadLocal mode and OSIV mode (53), threadlocalosiv

ThreadLocal: maintain local variables of the thread.

ThreadLocal is not a thread. It is a Map. Objects can be saved.

The object it saves is only related to the current thread.

If you do not want to transmit data when a Thread is not running, you can use ThreadLocal to save data related to this Thread.

 

Example of using ThreadLocal to save and retrieve data:

Public class BaseDemo {public static void main (String [] args) {// declare Map <Object key, Object value> // Object is the value, key is the reference of the current Thread = Thread. currentThread (); ThreadLocal <Object> tl = new ThreadLocal <Object> (); // save data tl. set ("Helllo"); // get data Object val = tl. get (); System. err. println (val );}}

When multiple threads access the same resource together, threadLocal is used to maintain the variables of a thread:

In an application project, there is usually only one (static) threadlocal instance:

Public class MyThreadLocal {// declare a unique ThreadLocal private static ThreadLocal <Object> tl = new ThreadLocal <Object> (); public static Object getObject () {// read data from tl first Object o = tl. get (); // if it has not been saved, map. get (Thread. currentThread (); if (o = null) {// generate a Random o = new Random (). nextInt (100); // put it in tl. set (o) ;}return o ;}public static void remove () {tl. remove ();}}

For the objects stored inside ThreadLocal. You can execute the remove (countless) method to delete objects related to the current thread. You can also choose not to execute:

Because: threadlocal uses weak references internally:

WeakReferences

 

Use ThreadLocal to manage transactions

 

Three-tier mode:

 

Serlvet (MVC-C)-Sevice (service layer)-dao (data access layer)

 

Write two dao statements and call the two dao statements in the service.

 

Make the first dao successful. To make the second dao fail, you must roll back.

 

 

Step 1: Develop two dao

Public class UserDao2 {public void save () {String SQL = "insert into users values (?,?,?) "; QueryRunner run = new QueryRunner (); try {run. update (performanceutils. getConn (), SQL, "U002", "Jack", "333") ;}catch (SQLException e) {throw new RuntimeException (e );}}}

Step 2: Develop the Service

Public class UserService {// declare two dao private UserDao1 dao1 = new UserDao1 (); private UserDao2 dao2 = new UserDao2 (); public void save () {dao1.save (); dao2.save ();}}

 

Step 3: implement a Servlet

Public class UserServlet extends HttpServlet {// declare service instance private UserService service = new UserService (); public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {service. save ();}}

Step 4: Modify ceceutils. java

Package cn. hx. utils; import java. SQL. connection; import javax. SQL. dataSource; import com. mchange. v2.c3p0. comboPooledDataSource; public class DataSourceUtils {// declare the local container private static ThreadLocal <Connection> tl = new ThreadLocal <Connection> (); private static DataSource ds; static {ds = // new ComboPooledDataSource ("itcast");} public static DataSource getDatasSource () {return ds;} public static Connection getConn () by default in the read c3p0-config.xml () {// obtain the data from the tl container first. If the current thread has saved the connection, the connecton Connection con = tl is returned directly. get (); if (con = null) {try {con = ds. getConnection (); // get a new connection from ds every time // put this con in tl. set (con);} catch (Exception e) {e. printStackTrace () ;}} return con ;}}

 

Step 5: declare a transformer to start the transaction in the transformer

Package cn. hx. filter; import java. io. IOException; import java. SQL. connection; import java. SQL. SQLException; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. servletResponse; import cn. itcast. utils. dataSourceUtils; public class TxFilter implements Filter {public void Init (FilterConfig filterConfig) throws ServletException {} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// get Connection con = null; // start transaction try {con = performanceutils in try. getConn (); // start the transaction con. setAutoCommit (false); // release chain. doFilter (request, response); // if no error occurs. Con. commit ();} catch (Exception e) {System. err. println ("error"); try {con. rollback ();} catch (SQLException e1) {e1.printStackTrace ();} throw new RuntimeException (e);} finally {try {con. close ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} public void destroy (){}}

Step 6: configure the browser to weeb. xml. Excessive consideration for a specific path

<filter>  <filter-name>tx</filter-name>  <filter-class>cn.itcast.filter.TxFilter</filter-class> </filter> <filter-mapping>  <filter-name>tx</filter-name>     <url-pattern>/tx/*</url-pattern>  </filter-mapping>

Step 7: Summary

When the timer starts a transaction, it is called a mode: OSIV mode.

OSIV-Open Session In View =-Open the Session with the database at the View layer. -Hibernate.-AOP

Step 8: optimization:

In ceceutls. java, a thread-related object is deleted in thredlocal:

Package cn. hx. utils; import java. SQL. connection; import javax. SQL. dataSource; import com. mchange. v2.c3p0. comboPooledDataSource; public class DataSourceUtils {// declare the local container private static ThreadLocal <Connection> tl = new ThreadLocal <Connection> (); private static DataSource ds; static {ds = // new ComboPooledDataSource ("itcast");} public static DataSource getDatasSource () {return ds;} public static Connection getConn () by default in the read c3p0-config.xml () {// obtain the data from the tl container first. If the current thread has saved the connection, the connecton Connection con = tl is returned directly. get (); if (con = null) {try {con = ds. getConnection (); // get a new connection from ds every time // put this con in tl. set (con);} catch (Exception e) {e. printStackTrace () ;}} return con;} public static void remove () {tl. remove ();}}
Call remove: public class TxFilter implements Filter {public void init (FilterConfig filterConfig) throws ServletException {} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException in TxFilter, servletException {System. err. println ("thread:" + Thread. currentThread (). getName (); // get Connection con = null; // start transaction try {con = DataSourceUtils in try. getCo Nn (); // start the transaction con. setAutoCommit (false); // release chain. doFilter (request, response); // if no error occurs. Con. commit ();} catch (Exception e) {System. err. println ("error"); try {if (e instanceof SQLException) {con. rollback ();} else {con. commit () ;}} catch (SQLException e1) {e1.printStackTrace ();} throw new RuntimeException (e);} finally {try {con. close (); DataSourceUtils. remove ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} public void destroy (){}}

 

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.