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 <code>0...size()-1</code>, returns
* the value from the <code>index</code>th key-value mapping that this
* SparseArray stores.
*
* <p>The values corresponding to indices in ascending order are guaranteed
* to be associated with keys in ascending order, e.g.,
* <code>valueAt(0)</code> will return the value associated with the
* smallest key and <code>valueAt(size()-1)</code> will return the value
* associated with the largest key.</p>
*
* <p>For indices outside of the range <code>0...size()-1</code>,
* the behavior is undefined.</p>
*/
@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()的赋值操作和删除操作
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<People> 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 + "";
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="每一个子线程都会执行遍历和删除的操作\n
遍历的操作是有所不同,删除都是值删除1个数据"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009900"
android:text="点击 测试 10000 次遍历,执行 sparseArray.valueAt(j);"
android:onClick="tryOnlyValueAt"
android:textAllCaps="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#990000"
android:text="(会奔溃概率高)点击 测试10000次 遍历,执行赋值语句 People people = valueAt(j)"
android:onClick="tryWithAssignment"
android:textAllCaps="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#999900"
android:text="(会奔溃但是概率小)点击 测试1000次 遍历,\n 执行判断后再进行赋值 \n
if(valueAt(j)!=null valueAt(j) instanceOf People)\n
People people1 = sparseArray.valueAt(j);"
android:onClick="tryWithAssignmentWithJudge"
android:textAllCaps="false"/>
</LinearLayout>