Deep understanding of Handler message mechanism Message.obtain ()

Source: Internet
Author: User
Tags garbage collection

Foreword: in our daily development work, it is inevitable that the message is transmitted between threads, and the most common way of implementation of this process is the handler message mechanism. Of course, this is not our focus today, and today we are going to focus on the intermediates ofMessaging: message. How do we get to the message object. Perhaps most students create a new object directly by using new Message () , and students who know about performance and efficiency may pass handler.obtainmessage () or Message.obtain () the way to get the message object. What is the difference between these methods? What is the difference between efficiency and performance. When you see this, you still have a face. Yes, then follow my thinking to continue to watch; If you still have a confident feeling, I can only say: big guy, little brother to pass tea to you. Don't talk much, cut to the chase.

Message Creation Method One: Message message = new Message ()
This approach is common and is a common way to create objects. Each time you need a message object to create a new object, each time to heap memory to open object storage space, after the object is used, the JVM is going to garbage collection of this discarded object. See here, you may say: We usually use the object is not the case, what a fuss. Do we usually operate objects in the way there are problems of efficiency and performance.

In the face of all kinds of questions, I just want to say: drink a cup of coffee to calm down, listen to me to explain to you. As the saying goes: Without contrast, there is no harm. There is no problem with the way we usually use it, but there are more efficient ways to get it.

Message creation mode two: Message message = Handler.obtainmessage ()
It says that the way to get message is more efficient. But why is that? Don't worry, below we from the source point of view for everyone to parse. First look at the handler.obtainmessage () Source:

Public final Message Obtainmessage ()
    {return
        message.obtain (this);
    }

Because the Obtainmessage method is a method of the handler class, this here refers to the Handler.obtainmessage object in the handler that invokes the Obtainmessage method: that is, Handler (). There is no clear about this, please refer to this usage details to see the detailed explanation. Then look at the obtain method source:

public static message obtain (Handler h) {message
        M = obtain ();
        M.target = h;
        return m;
    }

From the source can see, here is through the message class internal method obtain () to get this message object, and this is the next we want to explain the third way Message.obtain () call logic, We'll analyze it in detail next. Insert a digression: Target in the message class is a handler object that is used primarily for post-processing of post messages. For more information, please handler the message mechanism . Next we explain: Message.obtain () message creation mode three: Message message = Message.obtain ()
Open the Message class obtain method, the source code is as follows:

  public static message obtain () {
        synchronized (spoolsync) {
            if (sPool!= null) {message
                m = sPool;
                SPool = M.next;
                M.next = null;
                m.flags = 0; Clear In-use flag
                spoolsize--;
                return m;
            }
        }
        return new Message ();
    }

See here, maybe we are just a smattering. Because there are several key variables in the method to confuse us, first understand their meaning to help us better understanding, and then look at the definition of these variables:

    private static final Object Spoolsync = new Object ();
    private static message SPool;
    private static int spoolsize = 0;

Yes, see here, understand is much easier: Spoolsync : The main message is to add an object lock, not allow multiple threads to access both the message class and the obtain method, to ensure that the spool obtained is the latest. SPool: A single linked list that stores the message we recycle. The data structure of the message is mentioned in the handler messaging mechanism, so here spool is just the head node of the list. spoolsize: The length of a list of linked lists, that is, the number of message objects stored.

Understanding the meaning of these variables makes it easier to understand the obtain method. To understand the data structure of students, a look at the realization of the logic of the obtain method, it is the operation of the linked list. The specific logic is as follows: synchronized (spoolsync): Locks the object to ensure that only one thread at the same time uses the message. If (sPool!= null): Determines whether the SPool list is an empty list and, if it is empty, creates a message object to return directly, otherwise it enters the third step. linked list Operations : Removes the linked header node as a reused message object and the second node as the head node of the new list (SPool).

Message m = SPool;
 SPool = M.next;
 M.next = null;
The following figure:


4. The final step : The length of the list minus one, the third step to get the message back, for reuse, the execution code is as follows:

  spoolsize--;
  return m;

Summary : This is the details of getting the message object through the Obtain method. Getting the message object through the Obtain method allows the message to be reused, reducing the time to request space each time the message is fetched. At the same time, this will not be endless to create new objects, reduce the JVM garbage collection pressure, improve efficiency.

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.