×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / IT技术讨论 / Re #15734: how to lock a file in Java? I mean how java provide flock()?
    • Sorry, this is the first I hear method "flock()". Is there such a function in Java? Would you please give me further information or just let me know what you want to do?
      • 他是说文件访问的互斥,即一个进程读写文件时
        • 被禁止
      • OK, I guess(guess!) I understand you now. First, it depends on your OS. Sometimes your OS will do this work for you. Second, you may use key word "synchronized" to adjust a statement to let this statement(s) can be
        OK, I guess(guess!) I understand you now. First, it depends on your OS. Sometimes your OS will do this work(exclusively operate a file) for you. Second, you may use the key word "synchronized" to adjust statement(s) to let this statement(s) can be invoked by only one thread. So, a file can only be accessed by one user.
        May be I will send you short sample codes.
        • "synchronized" in Java programming can not completely solve the problem of file locking.
          "synchronized" in Java programming can not completely solve the problem of file locking. Suppose 1. there are two PCs on network where they can access a file on a file server on the same newwork. Or 2. There are two tasks running on the same PC and attempt to access a file simutaneously. How can "synchronized" do ...
      • 'HOW TO....?' is a typical english mistake we chinese speakers
        ..tend to make. The correct way is "how do you...?". Sorry for
        interrupting. I am taking an English course now, so I am very
        interested in finding our common mistakes
        • "How to" or "How do you"
          You can use "How to" as the title of a document. For example, "How to Lock a File in Java". But, if you want to ask a question, use: "How do you lock a file in Java?"
          • you are absolutely correct!
            we can still use 'how to' as a title or a sentence component such as 'do you know HOW TO ...?
            I pointed the HOW TO problem because I am used to say in the wrong way and many people is still makeing the same mistake very frequently. Especially in a interview, pay attention to 'how to'
    • Jabber's understanding.
      本文发表在 rolia.net 枫下论坛The following is my understanding of file locking problem in Java. It might
      be wrong.

      1) What is a file? A file is a resource, just like a database. So sometimes
      we need to pretect it from getting destroyed.

      2) In Java, a file at the native machine, as a resource, is wrapped into an Object, ---a File,
      or FileInpuStream, or FileOutputStream, or FileReader, or FileWriter, or RandomAccessFile...
      Some notes are in order here. a) If we use a File, we can use its public boolean setReadOnly()
      to make it readable only. This is not guaranteed to succeed, because the true file is out of the JVM.
      The caller of this method may fail because of the constraints of SecurityManager. If we succeed, the
      method return true; otherwise, it return false. b) If we create a RandomAccessFile, we may specify
      whether it is readable only or can be writable, too. Both a) and b) provide some ways to protect
      the file on the machine.

      3) The key word "synchronized" cannot be used to protect a file from being used by others.
      Look at the following code:

      File file = new File("xxx.txt");

      synchronized(file) { // operate on the file }

      Here JVM locks the File object (the wrapper of the real file) in JVM, not the real file on the
      operating system. One can cook up some code to confirm my statement here.

      4) Java Application (Applet, Servlet, EJB, ...) is only a process running on the native machine.
      The file is a resource on the native machine. Asking for a flock() function or something like it
      means to assign too much power to JVM. I GUESS this is one of the reasons that Java designers did not
      follow C/C++ here.

      5) In JVM, there is a SecurityManager. If we don't set a SecurityManger, JVM uses its default one.
      SecurityManger uses a policy file, which we can find one under JDK. SecurityManager does a lot of
      things, including assigning permission to operate on files. Just remind there is class
      called java.io.FilePermission. One needs to define it in policy files. If we just run some
      small examples, we seldom think about SecurityManager and policy files in Java.

      6) The constructors of the File related Java class throw a checked Exception called
      java.io.FileNotFoundException. This implies that java.io.* pakacgae has a very conservative
      design. Even the File is there on the native machine, it may not be available to us because of
      Security constraints. In turn, the power of locking, deleting, modifying a file is
      ultimately on the opertating system, on in the JVM. on the Java side, what we can do is
      to try to do something on the file. For instance, create a FileWriter and append some words
      to the real file on the operating system. However, this may fail if the system adminstrator
      have set the file to be readable only, even the SecurityManager allow us to write to the file.

      7) While Java design is so conservative with I/O? The answer is that Java is a networking
      language. In the distributed computing, people cannot allow Java has the same power as the
      operating system in dealing with the files.

      8) How far can we go in protecting a file? Since the file is a kind of resources,
      it usually should be shared. Locking a file as is done in C/C++ is too extreme.
      What Java can do is to ask its citizens---Java objects-- not to touch a certain file
      by use of policy file. Let me say there is a file called report.txt. Java has no luxury to say
      "hey, I am using it, you guys (Notepad, Textpad, WrdPad) don't touch it).
      A Java appication cannot be as powerful as an operating system. The File class
      has a setReadOnly() method because this is a harmless operation. However, it does not have
      something like setWritable(). If we want to make a file writable first to JVM, we should
      first change its previleg on the operating system, then carefully define policy file
      and grant write previlege to the right Java objects.

      9) Please don't criticise Java too early. We are Java lerners, not experts. My suggest is that
      we think more about security in the system.更多精彩文章及讨论,请光临枫下论坛 rolia.net
      • Jabber, thank you. You are an expert.
        • NOT TRUE
      • how to implement flock() in BBS forum like rolia? how to maintain the message number
        File file = new File("xxx.txt");

        synchronized(file) { // operate on the file }

        "synchronized" is a function?
        if it is a functin what class does it belong to?
        • message number
          usually message number is stored in a file
          suppose it is 1000
          servlet A read num=1000
          servlet B read num=1000
          servlet A increase num=1001
          servlet B increase num=1001
          servelt A write 1001
          servelt B write 1001 !

          the num should be 1002!
          • who can answer this question?I am just a undergraduation CS
            • sorry!It should be
              • Dear Servlet, I cannot understand your postings.
                One thing I can explain to you. synchronized is a key word in Java. It is not a function.
                • HOW to block other servlets(may be intants of same servlet) from reading and writing to a file when one servlet is accessing the same file.(mutual exclusive of file access)
                  • About "Servlet"'s message number ...
                    本文发表在 rolia.net 枫下论坛My discussion is as below:

                    As Jabber said above and as far as I know, directly control of file locking is outside of JVM.
                    If someone want to store the message number in a text or plain file and to use servlet to access the message number, I just know one way which can probably resolve what "Servlet" posted above: using native method in servlet (but this will involve non-Java programming and some level of platform-specific, so is not a pure Java solution). I do not know any more upto now.
                    I think the better way to solve this "message number stored in a text or plain file" problem is non-Java CGI or ISAPI or NSAPI.

                    Something which are about outside of control of JVM remains puzzled with me for a long time. The native method in a Java class is a way to get outside of JVM, and it seems very easy for the Java designers to implemented native methods to control almost any things outside of JVM. In fact I think they have done a lot: many of the "system" Java classes depend on the native methods. On the other side, I think they have not done a lot of important low level things which usually is platform-specific. I am not sure if there is any other reason besides the platform-specific for those Java designers to gave up so many important low level staffs.更多精彩文章及讨论,请光临枫下论坛 rolia.net
                  • 300 intsances of 50 servlets write to the same file ....
                    Let me distiquish two cases

                    1) If you have a servlet and a few of its instances, you can create a FileWriter as instance variable. Then, synchronzed on this FileWriter as you write sth into the file.
                    In such a way, those servlet instances write
                    to the file in turn.

                    2) If different servlts write to the same file,
                    you had better create a servlet for this business. This servlet contains a FileWriter. Design this servlet use the Singleton pattern. NEXT, NEXT, NEXT, you need to bind your servlet with ServletContext. Finally, use this servlet in other servlets whenever you need to write to the file. This is the solution I can figure out. Maybe there are better solutions.
                    • I have found the solution myself on java.sun.com. Use a new file as a semaphore. Through it have some drawback,but it is platform independence. thank you all
                      • Dear Servlet, can you give us the link for the solution at Sun's site? Thanks a million....
                        • Jabber, I read it, too.
                          In a synchronized block, create a new file---lock it;
                          To unlock it, just delete this file in aother synchronized block.
                          • I think we can have two strategies,1) within samWithin same VM use synchronized method. 2) Between two VM use new_file or other semaphore
                          • So simple? so easy? I am stunned.
                          • I get confused with something. The file is really locked inside JVM? I think I must misunderstand something important. Please let me know more details, thank you very much!