How to atomically rename a file in Java, even if the dest file already exists?

前端 未结 8 2112
难免孤独
难免孤独 2020-12-09 07:55

I have a cluster of machines, each running a Java app.

These Java apps need to access a unique resource.txt file concurently.

I need to atomical

8条回答
  •  天涯浪人
    2020-12-09 08:10

    If the purpose of the rename is to replace resource.txt on the fly and you have control over all the programs involved, and the frequency of replacement is not high, you could do the following.

    To open/read the file:

    1. Open "resource.txt", if that fails
    2. Open "resource.old.txt", if that fails
    3. Open "resource.txt" again, if that fails
    4. You have an error condition.

    To replace the file:

    1. Rename "resource.txt" to "resource.old.txt", then
    2. Rename "resource.new.txt" to "resource.txt", then
    3. Delete "resource.old.txt".

    Which will ensure all your readers always find a valid file.

    But, easier, would be to simply try your opening in a loop, like:

    InputStream inp=null;
    StopWatch   tmr=new StopWatch();                     // made up class, not std Java
    IOException err=null;
    
    while(inp==null && tmr.elapsed()<5000) {             // or some approp. length of time
        try { inp=new FileInputStream("resource.txt"); }
        catch(IOException thr) { err=thr; sleep(100); }  // or some approp. length of time
        }
    
    if(inp==null) {
         // handle error here - file did not turn up after required elapsed time
         throw new IOException("Could not obtain data from resource.txt file");
         }
    
    ... carry on
    

提交回复
热议问题