Search code examples
javasynchronizationpreferences

How to synchronized getter and setter from Preferences?


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?


Solution

  • 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.