美文网首页SystemUI
SystemUI问题分析——线程安全

SystemUI问题分析——线程安全

作者: Monster_de47 | 来源:发表于2018-11-05 17:29 被阅读172次

    前言

    线程安全就是在线程执行过程中不会产生共享资源的冲突。今天,就讲一讲SystemUI内一次线程安全问题。

    问题介绍

    在Android 8.1设备上进行mokey测试,发现systemUI在过程中出现crash,crahs信息如下:

    CRASH: com.android.systemui (pid 951)
    Short Msg: java.lang.IndexOutOfBoundsException
    Long Msg: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.get(ArrayList.java:437)
    at java.util.Collections$SynchronizedList.get(Collections.java:2461)
    at com.android.systemui.util.Utils.safeForeach(Unknown Source:8)
    at com.android.systemui.statusbar.policy.LocationControllerImpl$H.locationSettingsChanged(Unknown Source:17)
    at com.android.systemui.statusbar.policy.LocationControllerImpl$H.handleMessage(Unknown Source:6)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6523)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
    

    分析过程

    从上面log可以看出,在SystemUI中LocationControllerImpl.java发生了IndexOutOfBoundsException,接下来看下报错地方的相关代码逻辑:

    private ArrayList<LocationChangeCallback> mSettingsChangeCallbacks =
                new ArrayList<LocationChangeCallback>();
    
    private void locationSettingsChanged() {
            boolean isEnabled = isLocationEnabled();
            Utils.safeForeach(mSettingsChangeCallbacks,
                    cb -> cb.onLocationSettingsChanged(isEnabled));
     }
    
    public class Utils {
    
        /**
         * Allows lambda iteration over a list. It is done in reverse order so it is safe
         * to add or remove items during the iteration.
         */
        public static <T> void safeForeach(List<T> list, Consumer<T> c) {
            for (int i = list.size() - 1; i >= 0; i--) {
                c.accept(list.get(i));
            }
        }
    }
    

    从代码不难看出,mSettingsChangeCallbacks是一个线程不安全的List,虽然源码中已经通过倒着遍历的方式来避免线程安全问题,但是最终依然是执行了arrayList的get方法,如果此时的list发生变化,同样是有可能发生IndexOutOfBoundsException。

    为什么ArrayList线程不安全

    这里就需要通过源码来进行分析了,先看下ArrayList的部分源码:

    public class ArrayList<E> extends AbstractList<E>
            implements List<E>, RandomAccess, Cloneable, java.io.Serializable
    {
        /**
         * The array buffer into which the elements of the ArrayList are stored.
         * The capacity of the ArrayList is the length of this array buffer. Any
         * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
         * will be expanded to DEFAULT_CAPACITY when the first element is added.
         */
        // Android-note: Also accessed from java.util.Collections
        transient Object[] elementData; // non-private to simplify nested class access
    
        /**
         * The size of the ArrayList (the number of elements it contains).
         *
         * @serial
         */
        private int size;
    }
    

    ArrayList的实现主要就是用了一个Object的数组,用来保存所有的元素,以及一个size变量用来保存当前数组中已经添加了多少元素。接下来在看一下add是如何实现的:

    /**
      * Returns the element at the specified position in this list.
      *
      * @param  index index of the element to return
      * @return the element at the specified position in this list
      * @throws IndexOutOfBoundsException {@inheritDoc}
      */
    public E get(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    
        return (E) elementData[index];
    }
    

    由此看到get元素的时候,会比较index和当前的size,而这里的size会因为其他线程的add、remove发生改变,故出现文章最开始的IndexOutOfBoundsException。
    既然ArrayList无法满足线程安全的需求,那么这里需要一个新的集合来保存callback list,这里引入一个新的List——CopyOnWriteArrayList。CopyOnWriteArrayList是一个线程安全的集合,但是经过测试,依然会出现IndexOutOfBoundsException,报错信息如下:

    01-01 14:22:57.540 7670 7872 W Monkey : // CRASH: com.android.systemui (pid 1685)
    01-01 14:22:57.540 7670 7872 W Monkey : // Short Msg: java.lang.ArrayIndexOutOfBoundsException
    01-01 14:22:57.540 7670 7872 W Monkey : // Long Msg: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
    01-01 14:22:57.541 7670 7872 W Monkey : // Build Changelist: 1520946343
    01-01 14:22:57.542 7670 7872 W Monkey : // Build Time: 1520946339000
    01-01 14:22:57.548 7670 7872 W Monkey : // java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
    01-01 14:22:57.548 7670 7872 W Monkey : // at java.util.concurrent.CopyOnWriteArrayList.get(CopyOnWriteArrayList.java:385)
    01-01 14:22:57.548 7670 7872 W Monkey : // at java.util.concurrent.CopyOnWriteArrayList.get(CopyOnWriteArrayList.java:398)
    01-01 14:22:57.548 7670 7872 W Monkey : // at com.android.systemui.util.Utils.safeForeach(Unknown Source:8)
    01-01 14:22:57.548 7670 7872 W Monkey : // at com.android.systemui.statusbar.policy.LocationControllerImpl$H.locationSettingsChanged(Unknown Source:17)
    01-01 14:22:57.548 7670 7872 W Monkey : // at com.android.systemui.statusbar.policy.LocationControllerImpl$H.handleMessage(Unknown Source:6)
    01-01 14:22:57.548 7670 7872 W Monkey : // at android.os.Handler.dispatchMessage(Handler.java:106)
    01-01 14:22:57.548 7670 7872 W Monkey : // at android.os.Looper.loop(Looper.java:164)
    01-01 14:22:57.548 7670 7872 W Monkey : // at android.app.ActivityThread.main(ActivityThread.java:6523)
    01-01 14:22:57.548 7670 7872 W Monkey : // at java.lang.reflect.Method.invoke(Native Method)
    01-01 14:22:57.548 7670 7872 W Monkey : // at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    01-01 14:22:57.548 7670 7872 W Monkey : // at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
    01-01 14:22:57.548 7670 7872 W Monkey : //
    

    从上面log可以看出,同样在safeForeach的时候,对List进行get操作时出现了IndexOutOfBoundsException。这里再来看下CopyOnWriteArrayList的get()源码:

    /**
      * {@inheritDoc}
      *
      * @throws IndexOutOfBoundsException {@inheritDoc}
      */
    public E get(int index) {
         return get(getArray(), index);
    }
    

    可以看出来这里依然会出现IndexOutOfBoundsException的可能,那么前面说道CopyOnWriteArrayList是线程安全的,需要怎么实现呢?这里通过进一步分析源码发现COW机制通过Iterator来实现的:

    static final class COWIterator<E> implements ListIterator<E> {
         /** Snapshot of the array */
         private final Object[] snapshot;
    
        COWIterator(Object[] elements, int initialCursor) {
                cursor = initialCursor;
                snapshot = elements;
         }
    }
    

    显而易见,CopyOnWriteArrayList会把elements存入snapshot,使用者通过迭代器对List进行遍历。
    这里就要回到文章开始,SystemUI有一个safeForeach()的接口:

    public class Utils {
    
        /**
         * Allows lambda iteration over a list. It is done in reverse order so it is safe
         * to add or remove items during the iteration.
         */
        public static <T> void safeForeach(List<T> list, Consumer<T> c) {
            for (int i = list.size() - 1; i >= 0; i--) {
                c.accept(list.get(i));
            }
        }
    }
    

    前面说道,如果不通过迭代器遍历CopyOnWriteArrayList,get依然会出现IndexOutOfBoundsException,所以这里的safeForeach并不安全(google大大你可能写错啦~)。那么需要怎么修改呢?接下来为你解开谜题。

    for和foreach安全性

    众所周知,java中for循环有个威力增强版——foreach,那么这个foreach有什么神奇之处呢?接下来通过一段代码给大家剖析一下:

    int [] array = {1,2,3};
    for(int i : array){
      System.out.println(i);
    }
         
    List list = new ArrayList();
    list.add(1);
    list.add(2);
    list.add(3);
    for(Object obj : list){
        System.out.println(obj);
    }
    

    通过反编译工具,查看 class 文件内容:

    int array[] = {1,2,3};
       int [] array$ = array;
       for(int len$ = array$.length, i$ = 0; i$<len$; ++i$ )
       {
           int i = array$[i$];
           {
               System.out.println(i);
           }
       }
        
        
       List list = new ArrayList();
       list.add(1);
       list.add(2);
       list.add(3);
       for(java.util.Iterator i$ = list.iterator(); i$.hasNext();)
       {
           String s = (String) i$.next();
           {
               System.out.println(s);
           }
       }
    

    可以看出来foreach有以下特点
    1.对于数组,foreach 循环实际上还是用的普通的 for 循环
    2.对于集合,foreach 循环实际上是用的 iterator 迭代器迭代

    总结

    那么这里之前困扰的问题也迎刃而解了,通过foreach遍历CopyOnWriteArrayList即可实现线程安全:

    private void locationSettingsChanged() {
                boolean isEnabled = isLocationEnabled();
                /*Utils.safeForeach(mSettingsChangeCallbacks,
                        cb -> cb.onLocationSettingsChanged(isEnabled));*/
                for (LocationChangeCallback cb : mSettingsChangeCallbacks) {
                    cb.onLocationSettingsChanged(isEnabled);
                }
    }
    

    本文已独家授权ApeClub使用。

    相关文章

      网友评论

        本文标题:SystemUI问题分析——线程安全

        本文链接:https://www.haomeiwen.com/subject/nsxfxqtx.html