問題背景:
android項(xiàng)目在迭代的過程中,有個獲取定位的功能模塊拦英,一直有個異常居高不下蜒什。
嘗試修改了好幾版,都沒有解決掉這個問題
日志如下:
01-04 19:55:57.770 24194 24194 E AndroidRuntime: FATAL EXCEPTION: main
1501-04 19:55:57.770 24194 24194 E AndroidRuntime: Process: com.**, PID: 24194
1601-04 19:55:57.770 24194 24194 E AndroidRuntime: java.util.ConcurrentModificationException
1701-04 19:55:57.770 24194 24194 E AndroidRuntime: at java.util.ArrayList$Itr.next(ArrayList.java:860)
1801-04 19:55:57.770 24194 24194 E AndroidRuntime: at aiv$b.a(LocationManager.java:124)
1901-04 19:55:57.770 24194 24194 E AndroidRuntime: at com.baidu.location.LocationClient.b(Unknown Source:66)
2001-04 19:55:57.770 24194 24194 E AndroidRuntime: at com.baidu.location.LocationClient.a(Unknown Source:0)
2101-04 19:55:57.770 24194 24194 E AndroidRuntime: at com.baidu.location.LocationClient$a.handleMessage(Unknown Source:171)
2201-04 19:55:57.770 24194 24194 E AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:107)
2301-04 19:55:57.770 24194 24194 E AndroidRuntime: at android.os.Looper.loop(Looper.java:227)
2401-04 19:55:57.770 24194 24194 E AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:7668)
2501-04 19:55:57.770 24194 24194 E AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
2601-04 19:55:57.770 24194 24194 E AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
2701-04 19:55:57.770 24194 24194 E AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:960)
該錯誤日志其實(shí)很熟悉疤估,就是 fail-fast機(jī)制(java集合(Collection)中的一種錯誤機(jī)制)灾常。
場景復(fù)現(xiàn):
最原始代碼版本:
public final class LocationManager {
private static final class LocationManagerInstance {
private static final LocationManager INSTANCE = new LocationManager();
}
public static LocationManager getInstance() {
return LocationManagerInstance.INSTANCE;
}
private LocationManager() {
// do nothing
}
private static List<SoftReference<IBdLocationListener>> mWeakReferences = new ArrayList<>();
// mILocationListener;
private static MyLocationListener myListener = new MyLocationListener();
private LocationClient mLocationClient;
/**
* 開始申請 定位
*/
public void startLocate(IBdLocationListener locationListener, Application application) {
mLocationClient = new LocationClient(application);
if (mLocationClient != null) {
mWeakReferences.add(new SoftReference<>(locationListener));
if (locationListener != null) {
locationListener.startLocation();
}
LogUtils.i("start collect location info: thread name:" + Thread.currentThread().getName());
mLocationClient.start();
}
}
/**
* 取消注冊
*
* @param listener
*/
public void unRegisterListener(IBdLocationListener listener) {
synchronized (LocationManager.class) {
if (mWeakReferences == null || mWeakReferences.isEmpty()) {
return;
}
for (int i = mWeakReferences.size() - 1; i >= 0; i--) {
SoftReference<IBdLocationListener> itemListener = mWeakReferences.get(i);
if (itemListener != null && itemListener.get() != null && itemListener.get() == listener) {
mWeakReferences.remove(i);
}
}
}
}
//BDAbstractLocationListener
public static class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
if (mWeakReferences != null) {
Iterator<SoftReference<IBdLocationListener>> iterator = mWeakReferences.iterator();
while (iterator.hasNext()) {
SoftReference<IBdLocationListener> next = iterator.next();
if (next == null || next.get() == null) {
iterator.remove();
continue;
}
if (next.get() != null) {
next.get().onReceiveLocation(location);
}
}
}
}
});
}
}
}
由于是涉及到定位sdk,猜測是多線程沒加鎖導(dǎo)致的铃拇,數(shù)據(jù)不同步钞瀑。于是直接加鎖嘗試解決上線(本身概率性事件,復(fù)現(xiàn)概率不是很高)慷荔。
修改如下版本:
public final class LocationManager {
private static final class LocationManagerInstance {
private static final LocationManager INSTANCE = new LocationManager();
}
public static LocationManager getInstance() {
return LocationManagerInstance.INSTANCE;
}
private LocationManager() {
// do nothing
}
private static List<SoftReference<IBdLocationListener>> mWeakReferences = new ArrayList<>();
// mILocationListener;
private static MyLocationListener myListener = new MyLocationListener();
private LocationClient mLocationClient;
/**
* 開始申請 定位
*/
public void startLocate(IBdLocationListener locationListener, Application application) {
mLocationClient = new LocationClient(application);
synchronized (LocationManager.class) {
if (mLocationClient != null) {
mWeakReferences.add(new SoftReference<>(locationListener));
if (locationListener != null) {
locationListener.startLocation();
}
mLocationClient.start();
}
}
}
/**
* 取消注冊
*
* @param listener
*/
public void unRegisterListener(IBdLocationListener listener) {
synchronized (LocationManager.class) {
if (mWeakReferences == null || mWeakReferences.isEmpty()) {
return;
}
for (int i = mWeakReferences.size() - 1; i >= 0; i--) {
SoftReference<IBdLocationListener> itemListener = mWeakReferences.get(i);
if (itemListener != null && itemListener.get() != null && itemListener.get() == listener) {
mWeakReferences.remove(i);
}
}
}
}
//BDAbstractLocationListener
public static class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
synchronized (LocationManager.class) {
if (mWeakReferences != null) {
Iterator<SoftReference<IBdLocationListener>> iterator = mWeakReferences.iterator();
while (iterator.hasNext()) {
SoftReference<IBdLocationListener> next = iterator.next();
if (next == null || next.get() == null) {
iterator.remove();
continue;
}
if (next.get() != null) {
next.get().onReceiveLocation(location);
}
}
}
}
}
}
}
一直以為是線程不同步導(dǎo)致的雕什,但是發(fā)現(xiàn)加上鎖之后還是會報這個異常。
思考:
1.難道鎖對象不是同一個显晶?(確認(rèn)過確實(shí)是同一個)
2.同一個線程能同時 執(zhí)行兩處代碼监徘?(差點(diǎn)顛覆了我這么多年 理論的認(rèn)知)
哎,經(jīng)過網(wǎng)上查找資料吧碾。確實(shí)也是和自己理解的一樣:
參考資料:https://www.cnblogs.com/dolphin0520/p/3933551.html
對于該異常的結(jié)論:
1.在同一個線程中 確實(shí)也會報這個錯誤:
測試代碼如下:
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
Integer integer = iterator.next();
if(integer==2)
list.remove(integer);
}
}
}
2.多線程中更會報這個錯誤:
測試代碼如下:
public class Test {
private static ArrayList<String> testList = new ArrayList<>();
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 100000; j++) {
testList.add("" + j);
}
}
}).start();
}
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 10000; j++) {
for (String s : testList) {
System.out.println(s);
}
}
}
}).start();
}
}
}
思考:
通過測試以及 網(wǎng)上查閱資料凰盔,解決方法無非就是兩種(加鎖 或者使用 CopyOnWriteArrayList 線程安全的集合),
那為啥我的代碼倦春,還是報錯呢户敬??睁本?哎尿庐,苦惱....
最終結(jié)論:
經(jīng)過重新進(jìn)行了代碼邏輯走查,發(fā)現(xiàn):在遍歷所有監(jiān)聽器對象并且調(diào)用onReceiveLocation方法的時候呢堰。該對象的回調(diào)中抄瑟,又會調(diào)用unRegisterListener 方法,
查看unRegisterListener方法:發(fā)現(xiàn)該方法中會進(jìn)行 集合的刪除操作枉疼。
看到這皮假,這不就是單線程中 產(chǎn)生該異常的原因嘛撮抓。我擦犬辰。侠畔。毛萌。。尼瑪褪测。猴誊。。
這種迷惑性比較強(qiáng)的代碼侮措,確實(shí)有點(diǎn)坑爹懈叹。哎,學(xué)藝不精啊分扎。澄成。
最終修復(fù)版本代碼:
public final class LocationManager {
private static final class LocationManagerInstance {
private static final LocationManager INSTANCE = new LocationManager();
}
public static LocationManager getInstance() {
return LocationManagerInstance.INSTANCE;
}
private LocationManager() {
// do nothing
}
private static List<SoftReference<IBdLocationListener>> mWeakReferences = new ArrayList<>();
// mILocationListener;
private static MyLocationListener myListener = new MyLocationListener();
private LocationClient mLocationClient;
/**
* 開始申請 定位
*/
public void startLocate(IBdLocationListener locationListener, Application application) {
mLocationClient = new LocationClient(application);
synchronized (LocationManager.class) {
if (mLocationClient != null) {
mWeakReferences.add(new SoftReference<>(locationListener));
if (locationListener != null) {
locationListener.startLocation();
}
mLocationClient.start();
}
}
}
/**
* 取消注冊
*
* @param listener
*/
public void unRegisterListener(IBdLocationListener listener) {
synchronized (LocationManager.class) {
if (mWeakReferences == null || mWeakReferences.isEmpty()) {
return;
}
for (int i = mWeakReferences.size() - 1; i >= 0; i--) {
SoftReference<IBdLocationListener> itemListener = mWeakReferences.get(i);
if (itemListener != null && itemListener.get() != null && itemListener.get() == listener) {
// 在此處不要刪除,重置為null笆包。在調(diào)用處,使用iterator 遍歷的時候略荡,刪除
mWeakReferences.set(i, null);
}
}
}
}
//BDAbstractLocationListener
public static class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
synchronized (LocationManager.class) {
if (mWeakReferences != null) {
Iterator<SoftReference<IBdLocationListener>> iterator = mWeakReferences.iterator();
while (iterator.hasNext()) {
SoftReference<IBdLocationListener> next = iterator.next();
if (next == null || next.get() == null) {
iterator.remove();
continue;
}
if (next.get() != null) {
next.get().onReceiveLocation(location);
}
}
}
}
}
}
}
結(jié)論雖然是很簡單庵佣,但是排查過程中確實(shí)是很痛苦的。汛兜。巴粪。
做一下開發(fā)過程中的簡單記錄吧,加油V嗝8馗!