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

前端 未结 8 2118
难免孤独
难免孤独 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:09

    If this should be cross-platform I suggest 2 options:

    1. Implement an intermediate service that is responsible for all the file accesses. Here you can use several mechanisms for synchronizing the requests. Each client java app accesses the file only through this service.
    2. Create a control file each time you need to perform synchronized operations. Each java app that accesses the file is responsible checking for the control file and waiting while this control file exists. (almost like a semaphore). The process doing the delete/rename operation is responsible for creating/deleting the control file.

提交回复
热议问题