当我将值放入 Java 首选项时,它会自动刷新吗?
When I put value in a Java Preference does it automatically flush?
我正在使用 java.util.prefs.Preferences
来存储我的应用程序设置。这是我的示例代码-
private static final Preferences mPreferences
= Preferences.userRoot().node("lab_exam");
public static void setDefaultPath(java.nio.file.Path v)
{
mPreferences.put(DEFAULT_PATH, v.toString());
flush();
}
public static void flush()
{
try {
mPreferences.flush();
}
catch (BackingStoreException ex) {
Logger.getLogger(AppSettings.class.getName()).log(Level.SEVERE, null, ex);
}
}
每次输入新值时,我都会刷新 mPreference 以确保成功保存数据。现在我的问题是,Preference
是在我每次放东西时自动刷新,还是我做的是正确的?
来自 Preferences 的 Javadoc:
All of the methods that modify preferences data are permitted to operate asynchronously; they may return immediately, and changes will eventually propagate to the persistent backing store with an implementation-dependent delay. The flush method may be used to synchronously force updates to the backing store. Normal termination of the Java Virtual Machine will not result in the loss of pending updates -- an explicit flush invocation is not required upon termination to ensure that pending updates are made persistent.
所以,如果你想防止虚拟机异常终止时丢失,就用flush()
,否则就不需要了。请注意,每次更改后刷新 可能 会降低性能,但总的来说,我不希望您经常更新首选项,以至于这会成为一个问题。
我正在使用 java.util.prefs.Preferences
来存储我的应用程序设置。这是我的示例代码-
private static final Preferences mPreferences
= Preferences.userRoot().node("lab_exam");
public static void setDefaultPath(java.nio.file.Path v)
{
mPreferences.put(DEFAULT_PATH, v.toString());
flush();
}
public static void flush()
{
try {
mPreferences.flush();
}
catch (BackingStoreException ex) {
Logger.getLogger(AppSettings.class.getName()).log(Level.SEVERE, null, ex);
}
}
每次输入新值时,我都会刷新 mPreference 以确保成功保存数据。现在我的问题是,Preference
是在我每次放东西时自动刷新,还是我做的是正确的?
来自 Preferences 的 Javadoc:
All of the methods that modify preferences data are permitted to operate asynchronously; they may return immediately, and changes will eventually propagate to the persistent backing store with an implementation-dependent delay. The flush method may be used to synchronously force updates to the backing store. Normal termination of the Java Virtual Machine will not result in the loss of pending updates -- an explicit flush invocation is not required upon termination to ensure that pending updates are made persistent.
所以,如果你想防止虚拟机异常终止时丢失,就用flush()
,否则就不需要了。请注意,每次更改后刷新 可能 会降低性能,但总的来说,我不希望您经常更新首选项,以至于这会成为一个问题。