zienkikk
zienkikk

Reputation: 2414

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.

Upvotes: 10

Views: 4827

Answers (2)

hackbod
hackbod

Reputation: 91331

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.

Upvotes: 10

mfsiega
mfsiega

Reputation: 2872

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!

Upvotes: 5

Related Questions