Java Multithreading Basic Summary four: ThreadLocal

Source: Internet
Author: User
Tags final integer thread advantage

Speaking of Threadlocal, first of all, talk about the naming of this class. Intuitively it seems to be a thread of what relatives, but in fact it wants to express the meaning of the threads of local variables, that is, each thread its own variables. It serves as a JDK5 class that supports generics, primarily to use generics to encapsulate non thread-safe shared variables into secure, unshared variables that bind threads. This explanation I think we can probably guess how it's going to work: Initialize a shared variable when used by each thread, initializes a copy, and binds to the thread. All subsequent operations of the shared variable are the operations of the copy inside the thread, the full internal variable of the thread.

To achieve such a functional class design, the main technical point is to be able to copy and thread binding mapping, the program can safely find a copy of the current thread, modified securely bound to the thread. So we think of the storage structure of the map, where the threadlocal is using a thread-safe map form of storage to map the CurrentThread and variable replica one by one.

Now that you want to turn shared into unshared, the variable satisfies a scene: The state of the variable does not need to be shared. Stateless beans, for example, are safe between multithreading because there is no need to synchronize the state of the bean between threads, and to go with it (very irresponsible). But for a stateful bean to be careful between threads, thread A just saw that the state was a, trying to do things with a, thread B changed the state of the bean to B, and the result was not done. But if a stateful bean does not need to be shared, and each thread sees state A or B can make its own behavior, the option of not synchronizing is threadlocal.

The advantage of using threadlocal is that there is no need to worry about stateful beans sacrificing performance for consistency, and to use synchronized to limit the behavior of a single thread at the same time to the state of the bean. Instead, multiple threads are behaving according to the state of the copy of the bean they hold, and such a transition is inconceivable for concurrent support. For example, a DAO has a connection attribute, when multiple threads use the same instance of DAO, the problem comes: multiple threads with a connection, and it still has a connection, shutdown and so on the state of transition, we are very sensitive to think that this property is not safe! Look at this attribute, in fact, it is how to tell the thread of the brothers: I do not want to share these states, do not because of my state and do not dare to pursue together. Thread brothers are also depressed: if you have multiple births sisters how good Ah! At this time threadlocal brother came to say: "Vegetable, I take care of!" You thread a person a Connection, you want to shut off, want to connect on the connection, no longer have to complain that it put your connection off. The DAO instance does not have to feel inferior because it has an unsafe attribute. Of course Threadlocal's thinking is very good, but the official saying is that the initial performance is not good, with the map structure and thread.currentthread improvements, performance compared to the synchronized has a clear advantage. So if the use of jdk1.2,jdk1.3 and so on, do not imagine the Sparrow to become Phoenix ...

Then look at the nature of threadlocal and synchronized. The former does not care about the space, but can not bear to wait, the latter is indifferent to waiting, but just do not like to waste space. This also reflects a rule of the algorithm: usually use the scene to determine the ratio of time and space, both time-saving and provincial algorithms in most cases only exist in the illusion. Here is a simple example to explain, but personally feel that the design of the example is not very good, after the actual inspiration to replace it.

Java code

Import Java.util.concurrent.atomic.AtomicInteger;

/**
* User:yanxuxin
* Date:dec 14, 2009
* time:9:26:41 PM
*/
public class Threadlocalsample extends Thread {
Private OperationSample2 operationsample;

Public Threadlocalsample (OperationSample2 operationsample) {
This.operationsample = Operationsample;
}

@Override
public void Run () {
Operationsample.printandincrementnum ();
}

public static void Main (string[] args) {

Final OperationSample2 operation = new OperationSample2 ();//the shared Object for threads.

for (int i = 0; i < 5; i++) {
New Threadlocalsample (Operation). Start ();
}
}
}

Class Operationsample {
private int num;

Public synchronized void Printandincrementnum () {
public void Printandincrementnum () {
for (int i = 0; i < 2; i++) {
System.out.println (Thread.CurrentThread (). GetName () + "[id=" + num + "]");
num + + 10;
}
}
}

Class OperationSample2 {

private static threadlocal<integer> Threadarg = new Threadlocal<integer> () {
@Override
Protected Integer InitialValue () {
return 0;
}
};

public void Printandincrementnum () {
for (int i = 0; i < 2; i++) {
int num = Threadarg.get ();
Threadarg.set (num + 10);
System.out.println (Thread.CurrentThread (). GetName () + "[id=" + num + "]");
}
}
}

Class OperationSample3 {

private static final Atomicinteger uniqueId = new Atomicinteger (0);
private static threadlocal<integer> Threadarg = new Threadlocal<integer> () {
@Override
Protected Integer InitialValue () {
return Uniqueid.getandincrement ();
}
};

public void Printandincrementnum () {
for (int i = 0; i < 2; i++) {
int num = Threadarg.get ();
Threadarg.set (num + 10);
System.out.println (Thread.CurrentThread (). GetName () + "[id=" + num + "]");
}
}
}

Related Article

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.