Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How java uses ThreadLocal to store thread-specific objects

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how java uses ThreadLocal to store thread-specific objects. I believe most people don't know much about it, so share this article for your reference. I hope you can learn a lot after reading this article. Let's learn about it together.

Using ThreadLocal to store thread-specific objects

ThreadLocal provides thread-specific objects that can be accessed at any time throughout the thread life cycle, which greatly facilitates the implementation of some logic.

There are two main common uses of ThreadLocal:

Save thread context objects to avoid multi-level parameter passing

Save non-thread-safe objects to avoid multithreaded concurrent calls.

1. Save thread context objects to avoid multi-level parameter passing

Here, take the paging parameter setting and use in the source code of the PageHelper plug-in as an example.

Set the paging parameter code:

/ * * paging method class * / public abstract class PageMethod {/ * * Local paging * / protected static final ThreadLocal LOCAL_PAGE = new ThreadLocal (); / * * set paging parameter * / protected static void setLocalPage (Page page) {LOCAL_PAGE.set (page);} / * * get paging parameter * / public static Page getLocalPage () {return LOCAL_PAGE.get () } / * * start paging * / public static Page startPage (int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {Page page = new Page (pageNum, pageSize, count); page.setReasonable (reasonable); page.setPageSizeZero (pageSizeZero); Page oldPage = getLocalPage (); if (oldPage! = null & & oldPage.isOrderByOnly ()) {page.setOrderBy (oldPage.getOrderBy ()) } setLocalPage (page); return page;}}

Use paging parameter codes:

/ * * Virtual auxiliary dialect class * / public abstract class AbstractHelperDialect extends AbstractDialect implements Constant {/ * * get local pagination * / public Page getLocalPage () {return PageHelper.getLocalPage ();} / * * get paging SQL * / @ Override public String getPageSql (MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey pageKey) {String sql = boundSql.getSql (); Page page = getLocalPage () String orderBy = page.getOrderBy (); if (StringUtil.isNotEmpty (orderBy)) {pageKey.update (orderBy); sql = OrderByParser.converToOrderBySql (sql, orderBy);} if (page.isOrderByOnly ()) {return sql;} return getPageSql (sql, page, pageKey);}.}

Use the paging plug-in code:

/ * * query user function * / public PageInfo queryUser (UserQuery userQuery, int pageNum, int pageSize) {PageHelper.startPage (pageNum, pageSize); List userList = userDAO.queryUser (userQuery); PageInfo pageInfo = new PageInfo (userList); return pageInfo;}

If you want to pass the paging parameters to the query statement step by step through the function parameters, it is impossible to achieve it unless you modify the MyBatis-related interface functions.

two。 Save non-thread-safe objects to avoid multithreaded concurrent calls

When writing the date formatting tool function, the first thing that comes to mind is as follows:

/ * * date mode * / private static final String DATE_PATTERN = "yyyy-MM-dd"; / * * format date function * / public static String formatDate (Date date) {return new SimpleDateFormat (DATE_PATTERN) .format (date);}

Initializing DateFormat for each call results in poor performance. The definition of DateFormat as a constant is written as follows:

/ * date format * / private static final DateFormat DATE_FORMAT = new SimpleDateFormat ("yyyy-MM-dd"); / * format date function * / public static String formatDate (Date date) {return DATE_FORMAT.format (date);}

Because SimpleDateFormat is not thread-safe, when multiple threads call the formatDate function at the same time, the return result is not as expected. If you use ThreadLocal to define thread-specific objects, the optimized code is as follows:

/ * * Local date format * / private static final ThreadLocal LOCAL_DATE_FORMAT = new ThreadLocal () {@ Override protected DateFormat initialValue () {return new SimpleDateFormat ("yyyy-MM-dd");}}; / * format date function * / public static String formatDate (Date date) {return LOCAL_DATE_FORMAT.get () .date (date);}

This is implemented before there is no thread-safe date formatting tool class. After JDK8, it is recommended to use DateTimeFormatter instead of SimpleDateFormat because SimpleDateFormat is thread-safe and DateTimeFormatter is thread-safe. Of course, you can also use thread-safe date formatting functions provided by third parties, such as apache's DateFormatUtils utility class.

Note: ThreadLocal has a certain risk of memory leakage, so try to call the remove function to clean up the data before the end of the business code.

These are all the contents of the article "how java uses ThreadLocal to store thread-specific objects". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report