一、问题背景
当一个app中存在多个进程时例如存在 主进程,辅进程两个进程,两个进程都会去向a文件中写入数据。但是我们业务中希望每次仅允许有一个进程向a文件写入内容。即当主进程写入时,辅进程要等待主进程写完之后才可以写入,防止出现并发修改导致数据异常的问题。
在实际的场景上,例如在我们的项目中未使用mmkv之前,kv存储是自行实现的多进程并发的sp。
二、实现方案
1、方案1:仅一个进程负责写
将所有的写入操作调整到同一个进程中,这样就相当于规避了多进程并发问题。
我们可以通过提供一个contantprovider或者service来是实现这个功能。
以下是使用contentprovider的方式:
fileprovider
public class fileprovider extends contentprovider {
private static final string authority = "com.example.fileprovider";
private static final uri content_uri = uri.parse("content://" + authority + "/file");
// 文件锁,确保单进程写入
private static final object filelock = new object();
@override
public boolean oncreate() {
return true;
}
@override
public cursor query(uri uri, string[] projection,
string selection, string[] selectionargs, string sortorder) {
return null; // 不提供查询功能
}
@override
public string gettype(uri uri) {
return null;
}
@override
public uri insert(uri uri, contentvalues values) {
return null; // 不提供插入功能
}
@override
public int delete(uri uri, string selection, string[] selectionargs) {
return 0; // 不提供删除功能
}
@override
public int update(uri uri, contentvalues values,
string selection, string[] selectionargs) {
return 0; // 不提供更新功能
}
// 自定义方法:写入文件
@override
public bundle call(string method, string arg, bundle extras) {
if ("writetofile".equals(method)) {
string content = extras.getstring("content");
synchronized (filelock) {
writetofile(content);
}
bundle result = new bundle();
result.putboolean("success", true);
return result;
}
return super.call(method, arg, extras);
}
// 实际写入文件的逻辑
private void writetofile(string content) {
file file = new file(getcontext().getfilesdir(), "a.txt");
try (fileoutputstream fos = new fileoutputstream(file, true)) {
fos.write(content.getbytes());
} catch (ioexception e) {
e.printstacktrace();
}
}
}
注册
<provider
android:name=".fileprovider"
android:authorities="com.example.fileprovider"
android:exported="true" />
写入逻辑
private void writetofileviaprovider(string content) {
uri uri = uri.parse("content://com.example.fileprovider/file");
contentresolver resolver = getcontentresolver();
bundle extras = new bundle();
extras.putstring("content", content);
try {
bundle result = resolver.call(uri, "writetofile", null, extras);
if (result != null && result.getboolean("success")) {
log.d("fileprovider", "write successful");
}
} catch (exception e) {
log.e("fileprovider", "failed to write file", e);
}
}
使用service + binder的方式,代码比较简单,这里就不写了。
2、方案2:通过文件锁的方式
文件锁主要是利用filechannel、filelock来控制多进程并发。
关于 channel
channel 经常翻译为通道,类似 io 中的流,用于读取和写入。不用像bio那样,读数据和写数据需要不同的数据通道。
public interface channel extends closeable {
/**
* tells whether or not this channel is open.
*
* @return <tt>true</tt> if, and only if, this channel is open
*/
public boolean isopen();
/**
* closes this channel.
*/
public void close() throws ioexception;
}
我们常用的channel有:
- filechannel:文件通道,用于文件的读和写。
- datagramchannel:用于udp连接的接收和发送。
- socketchannel:把它理解为tcp连接通道,简单理解就是tcp客户端。
- serversocketchannel:tcp对应的服务端,用于监听某个端口进来的请求。
filechannel
filechannel 是 java nio (new i/o) 中的一个类,用于对文件进行高效的读写操作。它提供了比传统 fileinputstream 和 fileoutputstream 更灵活和高效的文件操作方式。
所有的nio操作始于通道,通道是数据来源或数据写入的目的地。其与 buffer 打交道,读操作的时候将 channel 中的数据填充到 buffer 中,而写操作时将 buffer 中的数据写入到 channel 中。
filechannel的获取方式:
通过fileinputstream/fileoutputstream
// 通过 fileinputstream/fileoutputstream (只读或只写)
fileinputstream fis = new fileinputstream("file.txt");
filechannel readchannel = fis.getchannel();
fileoutputstream fos = new fileoutputstream("file.txt");
filechannel writechannel = fos.getchannel();
通过randomaccessfile
// 通过 randomaccessfile
randomaccessfile raf = new randomaccessfile("file.txt", "rw");
filechannel channel = raf.getchannel();
通过filechannel.open()
filechannel channel = filechannel.open(paths.get("file.txt"), standardopenoption.read);
在我们示例代码中选择了使用 fileoutputstream 来获取filechannel。
filelock
filelock 表示文件或文件区域的锁,用于控制多个进程或线程对同一文件的并发访问。
锁的类型
- 共享锁 (shared lock) :多个进程可同时持有,用于读操作
- 排他锁 (exclusive lock) :一次只能由一个进程持有,用于写操作
通过文件锁的方式控制多进程并发的 示例代码:
public class filewriter {
private static final string file_path = "/path/to/your/file.txt";
public void writetofile(string content) {
file file = new file(file_path);
try {
fileoutputstream fos = new fileoutputstream(file, true);
filechannel channel = fos.getchannel())
// 获取独占锁
filelock lock = channel.lock();
try {
// 写入文件
fos.write(content.getbytes());
} finally {
// 释放锁
lock.release();
}
} catch (ioexception e) {
e.printstacktrace();
}
}
}
三、总结
以上简单介绍了一下两种控制多进程并发的方案。
其中使用contentprovider或者service的方式将所有的操作控制在同一个进程中的方案逻辑清晰,但是代码量比较多。尤其是使用service的方式,虽然上面我们每个给出示例代码,但是可以想象没新增一个进程都需要写相关的代码,写起来就比较啰嗦了。
而contentprovicer的方式,系统中也有很多相关的实现方案,例如更新媒体文件,更新联系人数据等。
使用文件锁的方式对于仅熟悉android不熟悉java的同学不容易想到,所以本篇也同时简单介绍了一下filechannel以及filelock。
到此这篇关于android实现多进程并发控制的两种方案的文章就介绍到这了,更多相关android多进程并发控制内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论