Filelock for Android filelock

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.