Java. NiO. channels. filelock is used to implement exclusive file read/write.

Source: Internet
Author: User

In a multi-threaded program, if a shared file is to be accessed or edited, how can I read and write files in the exclusive mode?

 

Using java. NiO. channels. filelock is a good method. The idea is to first create a file named genfile. LCK,

 

The getchannel (). trylock () method returns a filelock. If no one accesses the file, a reference not empty is returned,

 

If someone is accessing the service, null is returned,

 

In this way, the files being compiled by others will not be opened,

 

The Code is as follows:

 

Private Static final string gen_lck_file = "genfile. LCK ";

Private Static filelock genlock = NULL;

Public static void main (string ARGs []) {

Try {
// Acquire an exclusive lock, assure manager is stand alone
Genlock = new fileoutputstream (gen_lck_file). getchannel (). trylock ();

If (null! = Genlock ){
// Open the file you want!
} Else {
System. Err. println ("this file has been open but other person! ");
}
} Catch (filenotfoundexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
} Finally {
If (null! = Genlock ){
Try {
Genlock. Release ();
// Delete the lock file
New file (gen_lck_file). Delete ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}
}

 

It is prompted that genfile. LCK only provides a locked file to determine whether the file is accessed. The file to be accessed is actually in the code.

 

// Open the file you want!

 

This line is processed!

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.