1.今天在做项目的时候,发现一个Bundle数据,因为异步操作的关系,导致了线程不安全修改而崩溃,看了下源码,Bundle,里面的实现是ArrayMap不是线程安全的,如果要解决这个崩溃,要在调用的地方,加锁处理,但是使用的地方太多,很容易加锁错误
于是自己就对Bundle,使用装饰模式做了一层简单的封装,
public class SaveBundle{
/**
* 读写锁保证线程安全
*/
private ReentrantReadWriteLock mLock;
Bundle mBundle;
public SaveBundle(@Nullable Bundle bundle) {
this.mBundle = bundle;
mLock = new ReentrantReadWriteLock();
}
/**
* 写操作
* @param bundle
*/
public void putAll(Bundle bundle) {
mLock.writeLock().lock();
try {
if (mBundle != null) {
mBundle.putAll(bundle);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.writeLock().unlock();
}
}
public void putBoolean(@Nullable String key, boolean value) {
mLock.writeLock().lock();
try {
if (mBundle != null) {
mBundle.putBoolean(key, value);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.writeLock().unlock();
}
}
public void putString(@Nullable String key, @Nullable String value) {
mLock.writeLock().lock();
try {
if (mBundle != null) {
mBundle.putString(key, value);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.writeLock().unlock();
}
}
public void putSerializable(@Nullable String key, @Nullable Serializable value) {
mLock.writeLock().lock();
try {
if (mBundle != null) {
mBundle.putSerializable(key, value);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.writeLock().unlock();
}
}
/**
*
* @param key
* @param value
*/
public void putInt(@Nullable String key, int value) {
mLock.writeLock().lock();
try {
if (mBundle != null) {
mBundle.putInt(key, value);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.writeLock().unlock();
}
}
public Serializable getSerializable(@Nullable String key) {
mLock.readLock().lock();
try {
if (mBundle != null) {
return mBundle.getSerializable(key);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.readLock().unlock();
}
return null;
}
public int getInt(String key, int defaultValue) {
mLock.readLock().lock();
try {
if (mBundle != null) {
return mBundle.getInt(key, defaultValue);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.readLock().unlock();
}
return defaultValue;
}
public int getInt(String key) {
return getInt(key, 0);
}
public boolean getBoolean(String key, boolean defaultValue) {
mLock.readLock().lock();
try {
if (mBundle != null) {
return mBundle.getBoolean(key, defaultValue);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.readLock().unlock();
}
return defaultValue;
}
public boolean getBoolean(String key) {
return getBoolean(key, false);
}
public String getString(@Nullable String key, String defaultValue) {
mLock.readLock().lock();
try {
if (mBundle != null) {
return mBundle.getString(key, defaultValue);
}
} catch (Exception e) {
Debug.e(e);
} finally {
mLock.readLock().unlock();
}
return defaultValue;
}
public String getString(@Nullable String key) {
return getString(key, "");
}
public Bundle getBundle() {
return mBundle;
}
}
这样封装的话就很简单的实现了线程安全操作。比较方便,这也是一种比较常见的设计方式