Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should a TypedArray be recycled?

This answer tells me that calling the recycle() method of a TypedArray allows for it to be garbage collected. My question is why TypedArray specifically needs a method for it to be garbage collected? Why can't it just wait to be garbage collected like a regular object?

like image 234
gsingh2011 Avatar asked Dec 10 '12 16:12

gsingh2011


People also ask

What is TypedArray recycle?

recycle basically means..free/clearing all the data associated with corresponding resource. In Android we can find recycle for Bitmap and TypedArray. If you check both source files then you can find a boolean variable "mRecycled" which is "false"(default value). It is assigned to "true" when recycle is called.

What is TypedArray?

The JavaScript TypedArray object illustrates an array like view of an underlying binary data buffer. There are many number of different global properties, whose values are TypedArray constructors for specific element types, listed below.

What is typed array Kotlin?

toTypedArray(): Array<T> Returns a typed array containing all of the elements of this collection. Allocates an array of runtime type T having its size equal to the size of this collection and populates the array with the elements of this collection.


2 Answers

This is required for caching purporse. When you call recycle it means that this object can be reused from this point. Internally TypedArray contains few arrays so in order not to allocate memory each time when TypedArray is used it is cached in Resources class as static field. You can look at TypedArray.recycle() method code:

/**
 * Give back a previously retrieved StyledAttributes, for later re-use.
 */
public void recycle() {
    synchronized (mResources.mTmpValue) {
        TypedArray cached = mResources.mCachedStyledAttributes;
        if (cached == null || cached.mData.length < mData.length) {
            mXml = null;
            mResources.mCachedStyledAttributes = this;
        }
    }
}

So when you call recycle your TypedArray object is just returned back to cache.

like image 56
Andrei Mankevich Avatar answered Oct 02 '22 12:10

Andrei Mankevich


@Andrei Mankevich I just check the newest version of Android SDK, and it seems there are some changes make to recycle(). Please check the below codes:

/**
 * Recycle the TypedArray, to be re-used by a later caller. After calling
 * this function you must not ever touch the typed array again.
 */
public void recycle() {
    if (mRecycled) {
        throw new RuntimeException(toString() + " recycled twice!");
    }

    mRecycled = true;

    // These may have been set by the client.
    mXml = null;
    mTheme = null;

    mResources.mTypedArrayPool.release(this);
}
like image 26
Sam003 Avatar answered Oct 02 '22 10:10

Sam003