3

I think that we are able to lock files for exclusive access as i saw this link: http://developer.android.com/reference/java/nio/channels/FileLock.html

I want to create a save/load a file both in a background process (service) and the real foreground app. They may try to access this file at the same time, in that case one should wait.

I couldn't find a real sample for FileLock on android, i just read many threads that this is not possible on Android. But if so, why the documentation has a section for "FileLock"?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
frankish
  • 6,738
  • 9
  • 49
  • 100

4 Answers4

7

This works on normal Java application:

File file = ...;
FileInputStream fis = new FileInputStream(file); // or FileOutputStream fos = new FileOutputStream(file);
FileLock lock = fis.getChannel().lock(); // or FileLock lock = fos.getChannel().lock();

// do whatever you want with the file

lock.release();
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Can i mix FileOutputStream and FileInputStream ? will both return the same channel number? – frankish Feb 28 '13 at 18:51
  • So this will work between processes, right? (I mean, 2 seperate process will wait each other) – frankish Feb 28 '13 at 18:56
  • @frankish Try [`lock.isShared()`](http://developer.android.com/reference/java/nio/channels/FileLock.html#isShared()). – Eng.Fouad Feb 28 '13 at 19:02
  • 1
    On android 21 getChannel() returns a write-only FileChannel that shares its position with this stream. So no way to lock when reading. You'll get exception if you'll try to do it: FileInputStream fis = getActivity().openFileInput(fname); FileLock lock = fis.getChannel().lock(); //exception here – Deepscorn Apr 15 '15 at 22:06
5
  1. You could try lock() with blocking, and trylock() without blocking
  2. FileLock does not work on FileInputStream.
  3. In Android, FileLock works between processes, but does not work between threads in a process.
Bucket
  • 7,415
  • 9
  • 35
  • 45
kevinems
  • 154
  • 1
  • 5
  • What do processes in the context of Android actually mean? When I close the app and start it again, is it the same process? – AlexSee Mar 28 '18 at 09:31
2

FileLock does work on FileInputStream BUT only if acquired as a shared lock.

  FileInputStream fis = new FileInputStream(file + ext);
  FileChannel fileChannel = fis.getChannel();
  FileLock fileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, /*shared*/true);

Actually this makes sense. Shared lock means that there could be any number of simultaneous readers, but no writers allowed. While default exclusive lock gives process exclusive access to writing. As you can't write with FileInputStream, you have to acquire shared lock on it.

Kurovsky
  • 1,081
  • 10
  • 25
1

I think file locking works on "internal" phone memory but doesn't work on SD card.

Sergey Galin
  • 426
  • 6
  • 8