问题场景:
消息中心批量删除历史数据,偶现删不掉的情况。
消息中心的数据存储在数据库中,在删除数据时,由于是批量操作,可能这时候有新消息过来,就会插入新数据,这样就出现多线程操作数据库的情况。在插入,删除数据库的位置加锁之后,还是有问题。
后面发现由于推送模块是在独立的进程里面,多进程操作数据库,所以这里加锁就没啥用了。
解决办法:
1.使用文件锁
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {try {final File lockFile = new File(Objects.requireNonNull(getContext()).getExternalCacheDir(), "lock.txt");if(!lockFile.exists()) {lockFile.mkdirs();}RandomAccessFile raf = new RandomAccessFile(lockFile, "rw");FileChannel channel = raf.getChannel();FileLock fileLock = channel.tryLock();if (fileLock != null) {return super.applyBatch(operations);}} catch (Exception e) {}return null;}
2.android中的sqlite数据库是支持事务处理的,这里也可以使用事务来保证批处理数据库的原子性
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {SQLiteDatabase db = mDBHelper.getWritableDatabase();ContentProviderResult[] result;db.beginTransaction();try {result = super.applyBatch(operations);db.setTransactionSuccessful();} finally {db.endTransaction();}return result;}
总结:
ContentProvider的applyBatch方法并不能保证原子性,可以重写applyBatch方法加上事务逻辑来保证数据库批处理的原子性。