For example, there is a class in which two methods, one RECORDS an object to a file, and the other READS whether an error can occur, while simultaneously writing and READING a file, I know that when RECORDING, a new file is created and the old one is overwritten, or how ? And another method will be read from the old file, or from a new one. But what if a new file doesn’t have time to be created during the recording, and another method starts READING the incompletely created file? Thanks in advance for the answers.

class Saver { @SuppressWarnings("unchecked") public synchronized <P, V> Optional<Map<P, V>> deserializationOf(String mapName) throws IOException, ClassNotFoundException { try { FileInputStream fileInputStream = new FileInputStream(mapName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Map<P, V> map = (Map<P, V>) objectInputStream.readObject(); objectInputStream.close(); return Optional.of(map); } catch (IOException | ClassNotFoundException e) { return Optional.empty(); } } public synchronized <P, V> void serializationOf(String mapName, Map<P, V> map) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(mapName); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(map); objectOutputStream.close(); } } 
  • one
    Read and write to file - synchronized operations. Ie, if you are reading from a file, then another thread / process will not be able to write to it. - aleshka-batman
  • Do you need to synchronize these methods from above, or in this case you shouldn't be afraid? - Albert Petrov

0