Filelock to implement lock function on file

Source: Internet
Author: User


The use of filelock in a multithreaded environment to achieve the lock function of the file, to avoid multiple threads simultaneously operating the same file,


Program:

public class demo{

Filelock lock;

/* Read/write file * *

Public Rwfile () {

Lock=trylock ();

if (lock!=null) {

Lock succeeded

You can work with the file.

Unlock ();

}else{

Lock failure

}

}


/* Lock operation return NON-EMPTY = Lock Success * *

Private Filelock Trylock () throws IOException {

File LOCKF = new file (root, "xxx.dat"); The file to lock

Lockf.deleteonexit (); Specifies that the lock is released when exiting

Randomaccessfile file = new Randomaccessfile (LOCKF, "RWS"); Specify the file to lock

Filelock res = null;

try {

res = File.getchannel (). Trylock (); Attempt to get a lock on the file

The catch (overlappingfilelockexception oe) {//file is thrown by another thread lock

File.close ();

return null;

catch (IOException e) {

Log.error ("Cannot create lock on" + LOCKF, E);

File.close ();

Throw e;

}

return res;

}

/* Unlock Operation * *

private void Unlock () throws IOException {

if (This.lock = null)

Return

This.lock.release ();

Lock.channel (). Close ();

lock = null;

}

}

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.