如何同步从偏好设置中获取和设置的 getter 和 setter?

huangapple go评论77阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年4月10日 21:34:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/61141428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定