Preferences.flush() 和 Preferences.sync() 有什么区别?

What's the difference between Preferences.flush() and Preferences.sync()?

Preferences.flush()Preferences.sync()有什么区别?

来自 Javadoc (flush()):

Forces any changes in the contents of this preference node and its descendants to the persistent store. Once this method returns successfully, it is safe to assume that all changes made in the subtree rooted at this node prior to the method invocation have become permanent.

Implementations are free to flush changes into the persistent store at any time. They do not need to wait for this method to be called.

When a flush occurs on a newly created node, it is made persistent, as are any ancestors (and descendants) that have yet to be made persistent. Note however that any preference value changes in ancestors are not guaranteed to be made persistent.

If this method is invoked on a node that has been removed with the removeNode() method, flushSpi() is invoked on this node, but not on others.

sync():

Ensures that future reads from this preference node and its descendants reflect any changes that were committed to the persistent store (from any VM) prior to the sync invocation. As a side-effect, forces any changes in the contents of this preference node and its descendants to the persistent store, as if the flush method had been invoked on this node.

查看 java.util.prefs.FileSystemPreferencesjava.util.prefs.WindowsPreferences 的实现,flush() 仅调用 sync(),仅此而已。

处理其他 java.util.prefs 实现时(如果它们遵循规范):

默认情况下,所有修改Preferences的方法都是异步的,保证最终一致性。

flush() 用于同步执行修改,即通过阻塞执行。

sync() 用于提交本应异步发生的所有未决修改。换句话说,sync() 将阻止 执行并在继续之前强制状态一致。

为了避免在异常终止的情况下丢失未保存的数据,您应该在所有地方使用flush()。我无法评论这将如何影响您的代码效率。

flush()

Flush 基本上执行写入操作对首选项节点的任何更改到后备存储,包括所有子节点上的数据。

sync()

它确保内存中的当前版本的偏好节点与存储的版本匹配并且基本上Sync()阻止执行,所以使用flush()方法来避免未保存的数据。