Android之线程安全的单例模式,Adapter注意事项之引用传值

线程安全的单例模式
单位模式一般写法如下:

public static FestivalLab mInstance;
private FestivalLab() {
}
public static FestivalLab getInstance() {
    if (mInstance == null) {
        mInstance = new FestivalLab();
    }
    return mInstance;
}

这样写不是线程安全的,因为如果两个线程都进入到这里,会实例化两次。那么如何优化呢?

线程安全的单例模式:

public static FestivalLab mInstance;
private FestivalLab() {
}
public static FestivalLab getInstance() {
    if (mInstance == null) {
        synchronized (FestivalLab.class) {
            if (mInstance == null) {
                mInstance = new FestivalLab();
            }
        }
    }
    return mInstance;
}

这里用 synchronized 来进行锁定,同一时间只让一个线程进行实例化操作。

Adapter注意事项之引用传值
Adapter中经常会用到集合数据,先在Activity中获取集合数据,然后传给Adapter中构造适配器。
这里有一个特别需要注意的地方,就是java中集合数据是引用的方式传递的,如果在传给Adapter时数据不进行复制,在Activity中改变了集合数据(本意并不想改变Adapter中的数据),Adapter中的数据源也发生了变化,导致意想不到的错误(如索引越界)。

如果是这种情况,就要进行数据复制,示例如下:

private List<Festival> mFestivals = new ArrayList<>();
mFestivals.add(...);
public List<Festival> getFestivals() {
    return new ArrayList<>(mFestivals);
}
 
原文地址:https://www.cnblogs.com/lurenjiashuo/p/android-thread-safe-singleton-pattern.html