Integer and Threadlocal in Java

Source: Internet
Author: User

I. Integer1. Intro

Before starting, I still need to spit out the trough myself, I am really very dish!

    • He asked: * * Two integer Object = = is the comparison equal?
    • I answer: Object = = comparison, is a reference comparison, not equal!
    • He asked: Integercache what is this for?
    • I answer: ..., I am not very clear!!!

As can be seen from here, I am really very water!!
For these reasons there are others and so on, I began to write a blog, began to write a step on the pit!

2.IntegerCache

Before introducing this cache, let's first recognize the next integer. In Java, int is a basic numeric type that represents an integer, an integer is the representation of its object, and a wrapper class for int. Packaging classes exist in the JDK1, but in order to more convenient use of the integer, in the Java SE5 introduced automatic packaging and automatic unpacking mechanism, here no longer repeat, you can move to deep analysis of Java boxing and unpacking.
Java SE5 can be said to be a milestone version of the Java version iteration. In order to reduce the overhead of creating a large number of integers, improving performance, using the enjoy meta-mode, introducing an integer instance cache, and caching an integer instance of a range value of 128 to 127 in memory , The cache here is implemented using the auxiliary private Integercache static class in Integer.

Let's take a look at how to get a cached integer instance of the range 128 to 127, where the scope can be modified by the JVM startup parameters, which are described later

    • You can get//API calls by using the static valueof method
    • Can be obtained using the automatic packing mechanism, such as: Integer a = 100; //Autoboxing

This is based on the Java SE8, and then the implementation of Integercache:

/** * Cache to support the object identity semantics of autoboxing for values between * -128 and 127 (inclusive) as Requir Ed by JLS.  * * The cache is initialized on first usage. The size of the cache * May is controlled by the {@code-xx:autoboxcachemax=<size>} option. * During VM initialization, Java.lang.Integer.IntegerCache.high property * May is set and saved in the private system prop Erties in the * Sun.misc.VM class.    */private Static class Integercache {static final int low =-128;    static final int high;    Static final Integer cache[];        static {//high value is configured by property int h = 127;        String Integercachehighpropvalue = Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high");                if (integercachehighpropvalue! = null) {try {int i = parseint (Integercachehighpropvalue);                i = Math.max (i, 127);             Maximum array size is Integer.max_value   h = math.min (i, Integer.max_value-(-low)-1);            } catch (NumberFormatException nfe) {//If The property cannot is parsed into an int, ignore it.        }} high = h;        cache = new Integer[(high-low) + 1];        int j = Low;        for (int k = 0; k < cache.length; k++) cache[k] = new Integer (j + +);    range [ -128, 127] must be interned (JLS7 5.1.7) assert Integercache.high >= 127; } private Integercache () {}}

As can be seen from Java docs, this class is designed to support the caching of instances where the range of 128 to 127 is automatically wrapped.
When the cache is initialized for the first time, the size of the cache can be controlled by the JVM parameters -XX:AutoBoxCacheMax=size , and the Integercache high can be more flexible by setting the system attribute variables at the start of the JVM java.lang.Integer.IntegerCache.high . Integercache executes a static statement block when the class constructor is initialized, and then uses the For loop to start from low to constant self-gaga and then into the cache array.
Choose from 128 to 127 range because the values in this range are more commonly used!

Introduction to Here, I believe it is not difficult to see how funny my answer is, I sit idle thought I was right!
Speaking here, I have some regrets, last night to see a set of Fire shadow, just came in and Penn's dialogue, Payne to once the master of the words, although is paranoid, but admittedly is true.
Payne referred to himself as a God, and also as a mortal, said that the human cognition has limitations, living in a small space to think of their own knowledge is right, but from the perspective of God, the human cognition is wrong and stupid.
The purpose here is simply to think about what Payne said in our real life: indeed, when we have limited cognition, we think that the integer two object = = comparison, should be unequal, but because of limited technical mastery.

Off the subject, the introduction of a story, the main thing is to engrave, the lesson: do not take things as a matter of course, to think about its essence and principle; don't jump to conclusions, beware!

Not only Integer,short, Byte, Long, char all have the corresponding cache. But the cache for byte, short, long has a fixed range: 128 to 127;char cache:0 to 127.

Reference
Understanding the caching strategy for Java integers

Two. ThreadLocal

I do not repeat here what threadlocal is, solve what problems, the principle of implementation, application scenarios, online blog is very rich, can move to deep analysis of threadlocal.
This is primarily an analysis of the problem of threadlocal sharing in parent-child threads.
Threadlocal does not provide support for the value stored in threadlocal of a child thread sharing parent thread, threadlocal The Get method returns Key/value in Threadlocalmap related to the current thread, such as:

/* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ThreadLocal.ThreadLocalMap threadLocals = null;

Each thread Initializes a null reference to the THREADLOCALMAP when it is created. When a child thread is created Threadlocamap is null , it does not share the parent thread's threadlocalmap in Key/value.

However, there are many times when actual requirements need to share some state values of the parent thread. In this case, Java also provides support for this, only to say that the designers of the brain hole open.
The introduction of another Inheritablethreadlocal class in Java provides support for this, and the class name gives the best indication of purpose: inheritable threadlocal!

/* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ThreadLocal.ThreadLocalMap threadLocals = null;

Similarly, each thread is initialized when it is created inheritablethreadlocal
, and when the thread executes the initialized life cycle phase, the variable is initialized, such as:

    if (parent.inheritableThreadLocals != null)        this.inheritableThreadLocals =            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

During the initialization cycle of a thread, the threadlocal of the parent thread is first judged to be empty, and if not NULL, the inheritablethreadlocals of the child thread is created based on the inheritablethreadlocals of the parent thread.
The implementation of Inheritablethreadlocal is also very simple:

    • Childvalue: calculates the initialization value of a child thread, from which it is known that the child thread is using value in the parent thread, not a copy, and if a copy of the replica is required, you can inherit the override
    • Getmap: Returns the Inheritablethreadlocals held by the current thread
    • Createmap: If the current thread's inheritablethreadlocals is empty, create a

All of the above three APIs are rewritten threadlocal.

Integer and Threadlocal in Java

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.