The file lock seems simple, but it has encountered many problems in Android. After several attempts, we finally come to the correct solution:
First, let's look at how to get the filelock:
Filechannel. trylock ()
To obtain the file lock, first open the file channel. The channel can come from several places. I tried three places:
1. randomaccessfile
If the file does not exist, it will be created on its own. It is found that the file lock can be obtained in another thread after it is locked. The specific reason is unknown.
2. fileinputstream
If the file does not exist, an exception is thrown. The channel obtained is read-only and is not used to obtain the file lock.
3. fileoutputstream
The file lock is normal, and the multi-thread test is normal.
/*** Occupies a file lock ** @ Param file * @ return */public static filelock tryfilelock (File file) {try {checkparentpath (File ); // if the parent directory does not exist, the file lock fails to be created. fileoutputstream Fos = new fileoutputstream (File); filelock FL = FOS. getchannel (). trylock (); If (FL. isvalid () {fssdklog. I (log_tag, "tryfilelock" + file + "suc! "); Return FL ;}} catch (exception e) {fssdklog. E (log_tag," tryfilelock "+ file +" fail! "+ E. getmessage ();} return NULL;} public static void freefilelock (filelock FL, file) {If (file! = NULL) file. Delete (); If (FL = NULL |! Fl. isvalid () return; try {Fl. Release (); fssdklog. I (log_tag, "freefilelock" + file + "suc! ");} Catch (ioexception e ){}}
In Android, filelock only supports deadlocks between processes. Different threads in the same process are invalid, but threads in Windows can also be locked, please refer to the official explanation for the Implementation dependency platform of this interface!