Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent file access in Android

I know that many OSes perform some sort of locking on the filesystem to prevent inconsistent views. Are there any guarantees that Java and/or Android make about thread-safety of file access? I would like to know as much about this as possible before I go ahead and write the concurrency code myself.

If I missed a similar question that was answered feel free to close this thread. Thanks.

like image 323
zienkikk Avatar asked Mar 17 '12 00:03

zienkikk


2 Answers

Android is built on top of Linux, so inherits Linux's filesystem semantics. Unless you explicitly lock a file, multiple applications and threads can open it for read/write access. Unless you actually need cross-process file synchronization, I would suggest using normal Java synchronization primitives for arbitrating access to the file.

like image 83
hackbod Avatar answered Nov 13 '22 02:11

hackbod


The normal reading/writing functionality (FileInputStream, etc) does not provide any thread-safety AFAIK. To achieve thread-safety, you need to use FileChannel. This would look something like:

FileInputStream in = new FileInputStream("file.txt");
FileChannel channel = in.getChannel();
FileLock lock = channel.lock();
// do some reading
lock.release();

I would read the File Lock doc, and take care with the threading!

like image 5
mfsiega Avatar answered Nov 13 '22 02:11

mfsiega