File Lock Through Services

What is the best way to share a file between two writer services in the same application?

Edit: Sorry, I should have given more details, I think.

I have a service that saves entries to the buffer. When the buffer is full, it writes all the entries to the file (and so on). Another service start will come at some point and read the file (essentially copying / compressing it) and then empty.

+4
source share
2 answers

Here is a general idea of ​​what you can do:

public class FileManager { private final FileWriter writer = new FileWriter("SomeFile.txt"); private final object sync = new object(); public void writeBuffer(string buffer) { synchronized(sync) { writer.write(buffer.getBytes()); } } public void copyAndCompress() { synchronized(sync) { // copy and/or compress } } } 

You will need to do extra work to keep everything safe, but this is just a basic example to give you an idea of ​​how it looks.

+2
source

A common locking method is to create a second file in the same place as the main file. The second file may contain lock data or be empty. The advantage of having lock data (such as a process identifier) ​​is that you can easily spot an outdated lock file, which inevitably needs to be planned. Although the PID may not be the best amount of lock data in your case.

Example: Service1:

  • creates myfile.lock
  • creates / opens myfile

Service2:

  • Notes that myfile.lock present and pauses / blocks / waits
  • When myfile.lock leaves, it creates it and then opens myfile.

It would also be useful to verify that the file contains your information about the lock (identification specific to your service) immediately after its creation - just in case you wait for two or more services and create a lock at the same time. The latter succeeds, and therefore all other services should notice that their lock data is no longer in the file. Also - pause a few milliseconds before checking its contents.

0
source

Source: https://habr.com/ru/post/1315103/


All Articles