Vacantcell cache in the series of revealing Android principles

Source: Internet
Author: User

Friends who have performed operations on Android phones should have a deep impression on the Interaction Effects of the drag icon on the standby interface. For example, when the icon is dragged, the icon will be suspended and the position will be changed as it is dragged, after being dragged and released, the icon automatically finds a suitable space grid in the vicinity. Android uses a lot of programming skills to achieve this effect. The vacantcell cache discussed in this article is very representative.

Vacantcell caches objects of the same type. This mechanism is used to reuse allocated objects that have expired, so as to avoid frequent new objects. We know that object allocation is a task that consumes system resources, when a large number of objects need to be allocated frequently, the Android platform may encounter serious problems such as system slowdown due to insufficient heap memory and application error restart. Users drag icons on the standby interface frequently, while the Blank Mesh addressing algorithm in the android screen uses vacantcell cache to avoid frequent new large numbers of new objects.

The implementation of the vacantcell class is actually very simple, with less than 50 lines of implementation code:

static final class VacantCell {            int cellX;            int cellY;            int spanX;            int spanY;            // We can create up to 523 vacant cells on a 4x4 grid, 100 seems            // like a reasonable compromise given the size of a VacantCell and            // the fact that the user is not likely to touch an empty 4x4 grid            // very often             private static final int POOL_LIMIT = 100;            private static final Object sLock = new Object();            private static int sAcquiredCount = 0;            private static VacantCell sRoot;            private VacantCell next;            static VacantCell acquire() {                synchronized (sLock) {                    if (sRoot == null) {                        return new VacantCell();                    }                    VacantCell info = sRoot;                    sRoot = info.next;                    sAcquiredCount--;                    return info;                }            }            void release() {                synchronized (sLock) {                    if (sAcquiredCount < POOL_LIMIT) {                        sAcquiredCount++;                        next = sRoot;                        sRoot = this;                    }                }            }            @Override            public String toString() {                return "VacantCell[x=" + cellX + ", y=" + cellY + ", spanX=" + spanX +                        ", spanY=" + spanY + "]";            }        }

As you can see, vacantcell is actually a Java static internal class, and its external class is celllayout. the Java code path is \ packages \ apps \ launcher2 \ SRC \ com \ Android \ launcher2 \ celllayout. java (for details about how to download a single Android Gingerbread launcher module, refer to the blog Android source code download-use git
Clone to download a single directory ).

Next we will analyze how vacantcell's buffer mechanism is implemented.

Cellx, celly, spanx, and spany are the vertical and horizontal index numbers of the blank mesh and occupy the number of corresponding cell grids. We don't need to worry about them here.

Pool_limit defines the maximum value of vacantcell that can be cached. As mentioned in the comment, up to 523 vacantcell objects can be allocated, but for the screen mesh definition of 4x4, the buffer size of 100 should be sufficient. That is to say, the value of 100 is an empirical value, which can be modified flexibly according to the actual situation.

Slock is a Java object mainly used for synchronization control. We don't need to worry about it.

Sacquiredcount is a very important variable. It is actually a counter that counts in real time how many vacantcell object values are currently cached. According to this counter and pool_limit, the cache object cannot exceed the upper limit of pool_limit.

Sroot and next are two key references for caching vacantcell object chain storage, which respectively indicate the reference of the table header of the vacantcell object linked list and the next object linked to the specific vacantcell object.

Now we will introduce two key static methods of vacantcell cache: acquire () and non-static method release ().

When a new vacantcell object is required, launcher calls the static method acquire () of the static internal class vacantcell to obtain the new vacantcell object. Note that obtaining the new object here is not a new vacantcell object, but acquire. Let's look at the internal acquire method. When sroot is null, it is directly new vacantcell and return directly, because no cache is available at this time. When sroot is not null, this means that the cached vacantcell object exists. Then, directly retrieve the object pointed to by sroot from the linked list and use the object pointed to by sroot as the new header sroot, at the same time, the number of sacquiredcount is reduced by 1. This is actually a typical operation to delete a table header from a linked list. I believe that anyone familiar with the data structure will not be unfamiliar with this operation.

If the acquire () method provides how to use vacantcell chain cache, the release () method solves the problem of how to build vacantcell chain cache. We can see that the vacantcell object is added to the chain cache only when the value of sacquiredcount <pool_limit. Adding the current vacantcell object to the chain storage is also very easy. It points the next of the current vacantcell object to the original header, directs the static sroot application to the current object, and adds sacquiredcount to 1. That is to say, this operation is to insert the current vacantcell object into the table header of the vacantcell linked list.

So how to use this vacantcell object cache? First, when a new vacantcell object is required, call the static method acquire () of vacantcell to obtain the object instead of the new vacantcell object. Second, when a vacantcell object has expired, when no longer needed, call the release () method of this object to add this unnecessary object to the cache.

It should be noted that, if the new vacantcell object is used directly, there will be no direct problems, but this means that the vacantcell cache mechanism is not used. If an object is not needed, the release () call will not be displayed () this means that this object will not be added to the vacantcell cache linked list. If there is no reference association between nodes in the linked list, this object will be automatically reclaimed by Android Dalvik virtual machine as garbage.

This article analyzes in detail the implementation principle of vacantcell cache in the android launcher module. When we need to frequently construct and release a large number of Java objects of the same type, we will consider using a similar cache mechanism, in some cases, this can effectively solve the problem of memory insufficiency caused by frequent object allocation.

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.