如何从首选项同步 getter 和 setter?

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() {
        // 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;
    }
}

根据我的理解,将 synchronized 写入 getter 和 setter 是不正确的,对吗?什么是有效的解决方案?

首选项是线程安全的,可以从多个线程访问而无需同步共享资源。您可以在写入时调用 flush() 以确保立即进行更改。与其创建像 isDarkMode 这样的 class 成员,不如直接引用 Preferences。