英文:
How to synchronized getter and setter from Preferences?
问题
使用Java,我正在使用Preferences
来存储一些应用程序数据。我想在运行时将配置存储在变量中。但是当我需要设置一个值时,如何实现同步?
这只是一个非常简单的示例,以理解我的问题:
public class Configuration {
private static Preferences preferences = Preferences.userRoot().node("nodeName");
private boolean isDarkMode;
public Configuration() {
// 获取布尔值,如果不存在则返回false
this.isDarkMode = preferences.getBoolean("DARK_MODE", false);
}
// 用户将设置更改为暗模式,程序需要设置该值以进行存储
// TODO 如何同步此方法?
public static void setDarkMode(boolean b) {
preferences.putBoolean("DARK_MODE", b);
this.isDarkMode = b;
}
public static boolean isInDarkMode() {
return isDarkMode;
}
}
根据我的理解,仅在getter和setter上写上synchronized
是不正确的,对吗?有什么有效的解决方案?
英文:
Using Java I am using Preferences
to store some application data. I want to store the configuration in variables during runtime. But when I need to set a value, how can I implement synchronization?
This is just a very simple example to understand my question:
public class Configuration {
private static Preferences preferences = Preferences.userRoot().node("nodeName");
private boolean isDarkMode;
public Configuration() {
// Get boolean value or return false if it does not exist
this.isDarkMode = preferences.getBoolean("DARK_MODE", false);
}
//User changes setting to dark mode and the program needs to set the value to store it
//TODO How can I synchronize this method?
public static void setDarkMode(boolean b) {
preferences.putBoolean("DARK_MODE", b);
this.isDarkMode = b;
}
public static boolean isInDarkMode() {
return isDarkMode;
}
}
For my understanding it is not correct to just write synchronized
to getter and setter, is it? What is a valid solution?
答案1
得分: 1
Preferences是线程安全的,可以从多个线程访问,无需同步共享资源。您可以在写入时调用flush()以确保立即进行更改。不需要创建类成员(如isDarkMode),直接引用Preferences即可。
英文:
Preferences is thread-safe and can be accessed from multiple threads without the need to synchronize shared resources. You can call flush() on write to ensure that the changes are made immediately. Instead of creating a class member like isDarkMode, reference Preferences directly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论