I came across the documentation of the flush () method, which states that the method is needed to force changes in the node. Isn’t the change per se applied instantly when writing to the Preferences? It means writing through

  • preferences.node(String name) - create node
  • preferences.put(String key, String value) - adding a key-value to the node
  • Preferences.importPreferences(InputStream is) - import preferences from a stream (file, for example)

I personally don’t understand the Java sources in terms of how the Preferences class works. Can anyone explain in which cases the preferences.flush() need to be applied and what happens if this is not done?

  • Look heir, FileSystemPreferences. There, the very first lines say that SYNC_INTERVAL defaults to once every 30 seconds, minimum - once a second. - Dmitry V. Nov.
  • The documentation says that when flush () is executed, you can be sure that the records are securely recorded, if you do not call and kill the process, you can lose something that is not yet recorded in the repository, the timing of the implementation synchronization is chosen independently. - Dmitry V. Nov.
  • @zRrr please! As I could. :) - Dmitry V.

1 answer 1

The documentation says that flush () when called should save all changes to the repository. In other words, after successful completion of the data, the user can be sure that the data will not be lost. If you do not call this method to kill the JVM process, you can lose what has not yet been recorded. Implementations of this abstract class are free to choose the frequency of calling this method, i.e. do not have to wait for the user to call it.

For example, if you look at the implementation of FileSystemPreferences, in the first lines you can see:

 /** * Sync interval in seconds. */ private static final int SYNC_INTERVAL = Math.max(1, Integer.parseInt( AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "java.util.prefs.syncInterval", "30")))); 

The default synchronization interval is 30 seconds, but not less than 1 second.

  • Thanks for the answer. Question after: if I write ( importPreferences(InputStream) ), and then immediately read the data from Preferences ( exportSubtree(OutputStream) ), can it be that not all data will be in the reading stream? - SeniorJD
  • If immediately after, in the same stream - should not. If you are trying to do this from another stream, you can. importPreferences causes ImportSubtree, which is synchronized across nodes. See the javadoc: exportSubtree: "... subtree" invocation of this method " - Dmitry V.