Java handles file lock processing for multiple people reading and writing files at the same time

Source: Internet
Author: User

Original reproduced from http://blog.csdn.net/gxy3509394/article/details/7435993

Recent projects have encountered concurrent access to a file read and write, but at the same time read and write errors, so I studied the Java file lock this mechanism directly paste code

I'm using a thread to simulate how people read and write at the same time.

Write a file

Package Com.dnion.test;import Java.io.file;import Java.io.ioexception;import java.io.randomaccessfile;import Java.nio.channels.filechannel;import java.nio.channels.filelock;import java.util.calendar;/** * @author ChB */public        Class Thread_writefile extends thread{public void run () {Calendar calstart=calendar.getinstance ();                File File=new file ("D:/test.txt");                                    try {if (!file.exists ()) file.createnewfile ();            Lock the file Randomaccessfile out = new Randomaccessfile (file, "RW");            FileChannel Fcout=out.getchannel ();            Filelock Flout=null;                    while (true) {try {flout = Fcout.trylock ();                Break                      } catch (Exception e) {System.out.println ("There are other threads that are manipulating the file, the current thread sleeps 1000 milliseconds");                  Sleep (1000); }} for (int i=1;i<=1000;i++) {sleep (10);                StringBuffer sb=new StringBuffer ();                Sb.append ("This is the first" +i+ "line, should have nothing wrong ha");            Out.write (Sb.tostring (). GetBytes ("Utf-8"));            } flout.release ();            Fcout.close ();            Out.close ();        Out=null;        } catch (IOException e) {e.printstacktrace ();        } catch (Interruptedexception e) {e.printstacktrace ();        } Calendar calend=calendar.getinstance ();    System.out.println ("Write files are spent" + (Calend.gettimeinmillis ()-calstart.gettimeinmillis ()) + "seconds"); }}

Read the file

Package Com.dnion.test;import Java.io.File;  Import Java.io.FileInputStream;  Import java.io.FileNotFoundException;  Import java.io.IOException;  Import Java.io.randomaccessfile;import Java.nio.channels.FileChannel;  Import Java.nio.channels.FileLock;  Import Java.util.Calendar; /** * @author CHB */public class Thread_readfile extends thread{public void run () {try {C              Alendar calstart=calendar.getinstance ();              Sleep (5000);                                File File=new file ("D:/test.txt");             Add a lock to the file Randomaccessfile fis = new Randomaccessfile (file, "RW");              FileChannel Fcin=fis.getchannel ();              Filelock Flin=null;                    while (true) {try {Flin = Fcin.trylock ();                Break                      } catch (Exception e) {System.out.println ("There are other threads that are manipulating the file, the current thread sleeps 1000 milliseconds");                  Sleep (1000);               }             } byte[] buf = new byte[1024];              StringBuffer sb=new StringBuffer ();                      while ((Fis.read (BUF))!=-1) {sb.append (new String (buf, "utf-8"));              BUF = new byte[1024];                            } System.out.println (Sb.tostring ());              Flin.release ();              Fcin.close ();              Fis.close ();                            Fis=null;              Calendar calend=calendar.getinstance ();          System.out.println ("Read files total" + (Calend.gettimeinmillis ()-calstart.gettimeinmillis ()) + "seconds");          }catch (FileNotFoundException e) {e.printstacktrace ();          } catch (IOException e) {e.printstacktrace ();          } catch (Interruptedexception e) {e.printstacktrace (); }      }  }

  

Call


Here we're going to explain the file lock.

We manipulate the file speed by randomaccessfile this random read stream there will be a bit slow, but not extremely large files can generally be ignored.

We get locks by FileChannel objects.

Trylock and Lock method

Trylock () is non-blocking, it tries to acquire a lock, but if it is not available, for example, because some other process already holds the same lock and does not share it, it will return directly from the method call.

Lock () is blocked, it is blocking the process until the lock can be obtained, or the thread that calls lock () is interrupted, or the channel that calls Lock () is closed.

Support for exclusive and shared locks must be provided by the underlying operating system. The type of lock can be queried by filelock.isshared (). In addition, we cannot get the lock on the buffer, only on the channel.

Overlappingfilelockexception and the scope of the lock

Lock lock on a file only works on this file for other files that are not valid

The locks held by a single Java virtual machine on a particular file do not overlap, that is, when different threads in the same JVM go to the same file for a lock, get the lock, obtain the lock, and the Trylock () method does not throw an exception, but acquires a lock value of NULL.

Different JVM or different operating system to obtain the same file lock, get the first to obtain the lock, after getting the thrown file overlap Lock exception "overlappingfilelockexception". This is not the case with Windows, and if Linux throws an exception: "Java.io.IOException:Permission denied"

The difference between a shared lock and an exclusive lock

Exclusive lock : Also known as row lock, if one thread obtains an exclusive lock on a file, then other threads can no longer acquire exclusive or shared locks on the same file until the exclusive lock is freed.
Shared locks : If a thread acquires a shared lock on a file, other threads can obtain a shared lock on the same file or a shared lock on the same file part of the content, but cannot get an exclusive lock

Other threads are unreadable and not writable when the A.txt file is exclusively locked

Other threads are readable and not writable when the A.txt file is added to a shared lock

How to get a shared lock

Fc.trylock (Position,size,isshare); The third parameter is true when a shared lock

Java handles file lock processing for multiple people reading and writing files at the same time

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.