Blankj / Blankj/AndroidUtilCode
CacheDiskStaticUtils多线程存储的时候有问题
- Dominant language
- Java
- Stars
- 33.6k
- Forks
- 10.6k
- PR merge metrics
- No merged PRs in 30d
Description
多个线程调用CacheDiskStaticUtils.put()存储数据的时候,文件写入有问题。排查发现UtilsBridge.writeFileFromBytes(file, value)是非线程安全的,大佬麻烦看一下
- AndroidUtilCode 的版本:utilcode:1.30.0
- 出现 Bug 的设备型号:MeiZu M6Note
- 设备的 Android 版本:API 25
## 问题代码
```
CacheDiskUtils.class
private void realPutBytes(final String key, byte[] value, int saveTime) {
if (value == null) return;
DiskCacheManager diskCacheManager = getDiskCacheManager();
if (diskCacheManager == null) return;
if (saveTime >= 0) value = DiskCacheHelper.newByteArrayWithTime(saveTime, value);
File file = diskCacheManager.getFileBeforePut(key);
UtilsBridge.writeFileFromBytes(file, value);
diskCacheManager.updateModify(file);
diskCacheManager.put(file);
}
```
## 测试代码
```
private int num = 0;
private Runnable mRunnable = () -> {
num++;
CacheDiskStaticUtils.put("save_test", num + "");
};
private void testSave() {
try {
Thread thread1 = new Thread(mRunnable);
Thread thread2 = new Thread(mRunnable);
Thread thread3 = new Thread(mRunnable);
Thread thread4 = new Thread(mRunnable);
Thread thread5 = new Thread(mRunnable);
Thread thread6 = new Thread(mRunnable);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
thread6.join();
} catch (Exception e) {
e.printStackTrace();
}
LogUtils.e("value:" + CacheDiskStaticUtils.getString("save_test") + " num:" + num);
}
```
## 截图
[

](url)
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.