Threadlocal is used to implement data sharing within a thread, that is, for the same program code, multiple modules share one piece of data while running in the same thread, while another data is shared while running in another thread.
Each thread invokes the set method of the global Threadlocal object, which is equivalent to adding a record to its internal map, where key is the respective thread, and value is the values passed in by the respective set method, which can be called threadlocal.clear () at the end of the thread. method, which frees up memory faster and does not call, because the associated threadlocal variable is automatically freed after the thread ends.
Threadlocal Application Scenarios:
1. Order Processing includes a series of operations: reduce the amount of storage, add a flow of accounts, modify the general ledger, these operations to complete in the same transaction, usually the same thread processing, if the accumulation of corporate receivables failed, you should roll back the previous operations, otherwise, commit all operations, This requires that these operations use the same database connection objects, and that the code for those operations is in a different module class.
2. Bank transfers consist of a number of column operations: reducing the balance of the transferred account, increasing the balance of the transferred account, both of which are to be done in the same transaction, they must use the same database connection object, and the code of the transfer and transfer operation is the method of two different account objects respectively.
3. For example, Strut2 Actioncontext, the same piece of code is called by different threads, the data that the code operates on is the state and data of each thread, and for different threads, the GetContext method gets the same object, and for the same thread, Regardless of how many times the GetContext method is called and in which module the GetContext method is taken, the same is obtained.
Experimental case: Define a globally shared threadlocal variable, and then start multiple threads to store an integer number in the threadlocal variable. What is the result of simultaneous access by different threads?
Threadlocal implementing thread-scoped shared variables