SparseArray 的 java.lang.Object cannot be cast to 报错 的模拟

java.lang.ClassCastException: java.lang.Object cannot be cast to bjpkten.parsearraydemo.MainActivity$People
        at bjpkten.parsearraydemo.MainActivity$3.run(MainActivity.java:105)
        at java.lang.Thread.run(Thread.java:764)

 

报错原因:

首先这个报错是因为,

1: SparseArray  删除的时候是假删除,只是将它标记为delete, 

2: 在多线程的情况下,看下面的valueAt()这个方法,因为不是线程安全的,所以可能会得到一个已经被删除的数据,

3: 这个时候这个数据因为已经删除了,已经变成了Object 类型了,如果这个时候再执行赋值语句就会导致这个时候报上面的错误。

 

/**
     * Removes the mapping from the specified key, if there was any.
     */
    public void delete(int key) {
        int i = ContainerHelpers.binarySearch(mKeys, mSize, key);

        if (i >= 0) {
            if (mValues[i] != DELETED) {
                mValues[i] = DELETED;
                mGarbage = true;
            }
        }
    }


 /**
     * Given an index in the range 0...size()-1, returns
     * the value from the indexth key-value mapping that this
     * SparseArray stores.
     *
     * 

The values corresponding to indices in ascending order are guaranteed * to be associated with keys in ascending order, e.g., * valueAt(0) will return the value associated with the * smallest key and valueAt(size()-1) will return the value * associated with the largest key.

* *

For indices outside of the range 0...size()-1, * the behavior is undefined.

*/ @SuppressWarnings("unchecked") public E valueAt(int index) { if (mGarbage) { gc(); } return (E) mValues[index]; } /** * Returns the number of key-value mappings that this SparseArray * currently stores. */ public int size() { if (mGarbage) { gc(); } return mSize; } private void gc() { // Log.e("SparseArray", "gc start with " + mSize); int n = mSize; int o = 0; int[] keys = mKeys; Object[] values = mValues; for (int i = 0; i < n; i++) { Object val = values[i]; if (val != DELETED) { if (i != o) { keys[o] = keys[i]; values[o] = val; values[i] = null; } o++; } } mGarbage = false; mSize = o; // Log.e("SparseArray", "gc end with " + mSize); }

 

复现方法:

思路:创建多个子线程,多个子线程同时操作一个SparseArray的对象,对它进行valueAt()的赋值操作和删除操作

SparseArray 的 java.lang.Object cannot be cast to 报错 的模拟_第1张图片

package bjpkten.parsearraydemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseArray;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private SparseArray sparseArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    /**
     * 测试子线程使用 sparseArray.valueAt(j);
     * @param view
     */
    public void tryOnlyValueAt(View view) {
        init();
        for (int i = 0; i < 10000; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    for (int j = 0; j < sparseArray.size(); j++) {
                        //执行200次的valueAt操作
                        for (int k = 0; k < 20; k++) {
                            sparseArray.valueAt(j);
                        }
                    }
                    deleteOneData();
                }
            }).start();
        }
    }

    /**
     * 测试子线程使用 People people1 = sparseArray.valueAt(j); 进行赋值
     * @param view
     */
    public void tryWithAssignment(View view) {
            init();
            for (int i = 0; i < 10000; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //这里的sleep 不要太小,不要是1,或者10, 太小一次性就执行完了,不会有多个线程并行执行情况了
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        for (int j = 0; j < sparseArray.size(); j++) {
                            for (int k = 0; k < 20; k++) {
                                //执行20次*sparseArray.size  的倍数 valueAt的赋值
                                People people1 = sparseArray.valueAt(j);
                            }
                        }
                        //随便删除一条数据
                        deleteOneData();
                    }
                }).start();
            }
    }


    /**
     * 测试先判断 if(sparseArray.valueAt(j)!=null && sparseArray.valueAt(j)instanceof People)
     * @param view
     */
    public void tryWithAssignmentWithJudge(View view) {
            init();
            for (int i = 0; i < 10000; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //这里的sleep 不要太小,不要是1,或者10, 太小一次性就执行完了,不会有多个线程并行执行情况了
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        for (int j = 0; j < sparseArray.size(); j++) {
                            for (int k = 0; k < 20; k++) {
                                //执行20次*sparseArray.size  的倍数 valueAt的判断赋值
                                if(sparseArray.valueAt(j)!=null && sparseArray.valueAt(j)instanceof People) {
                                    People people1 = sparseArray.valueAt(j);
                                }
                            }
                        }
                        //顺便删除一条数据
                        deleteOneData();
                    }
                }).start();
            }
    }

    private void deleteOneData() {
        int key = sparseArray.size() -1;
        if(key >0) {
            //删除一个数据
            sparseArray.delete(key );
        }
    }


    /**
     * init 初始化 SparseArray
     */
    private void init() {
        sparseArray = new SparseArray<>();
        for (int i = 0; i < 1000; i++) {
            sparseArray.put(i,new People(" name " + i));
        }
    }


    class People {
        People(String name){
            this.name = name;
        }

        String name;

        @Override
        public String toString() {
            return name + "";

        }
    }
}

 




    

    

 

你可能感兴趣的:(Android,开发点滴)