当前位置:网站首页>Analysis of ThreadLocal principle

Analysis of ThreadLocal principle

2020-11-06 01:32:13 itread01

What about today , Let's talk to you `ThreadLocal`. ### 1. What is it ? `JDK1.2` Provides a class of thread bound variables . ** His idea is : Clone each thread that uses this resource , Different threads use different resources , And the resources are independent of each other ** ### 2. Why ? ** Think about a scene **: When the database is connected , We're going to build a `Connection` Connect , Let different threads use . At this time, multiple threads will scramble for the same resource . In this case, multiple threads are competing for the same resource , Very common , There are only two common solutions :** Space for time , Time for space ** There is no way , You can't have both . Just like our `CAP` Theory , And one of the sacrifices , Guarantee the other two . For the above scenario, our solution is as follows : - Space for time : Create a connection for each thread . - Direct online work , Create a connection .(** Too much duplicate code **) - Use `ThreadLocal`, Tie a connection for each thread . - Time for space : Lock the current resource , Only one thread at a time can use this connection . Through `ThreadLocal` Bind a variable of the specified type to each thread , It's equivalent to thread privatization ### 3. How to use ? ```java ThreadLocal threadLocal = new ThreadLocal<>(); threadLocal.get(); threadLocal.set(1); threadLocal.remove(); ``` That's right , These four lines of code have put `ThreadLocal` How to use it is very clear . - `get` From `ThreadLocal` Take out an object owned by the current thread - `set` Bind an object to the current thread - `remove` Removes the current object bound by the current thread ** Remember to use after , must do remove, must do remove, must do remove** Why do you want to `remove`. I believe many partners have heard of `ThreadLocal` Can cause memory leak problems . That's right , So in order to solve this situation ,** So you know , Remove after use , Don't waste space ( Slag man is pleased )** See this , There are a lot of question marks on my head (** Children, do you have many question marks ?**) ** Why can cause memory leak ?** ** Why not remove It's a memory leak ** ** How does it mean that objects are tied to threads ** ** Why get What you get is the current thread, not the other thread ** ** How did it come true ???** Come on ,** Kaigan , The source code comes from ** ### 4. Original code interpretation Let's start with an idea :** If we write our own `ThreadLocal` How to write ?** Thread binds an object .** Isn't this what we all know `map` It's the opposite ?** With `Map` We can use the thread as `Key`, The object is `value` Add to a collection , And then all kinds of `get,set,remove` operation , Play as you want , Get it done .**

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢