Slei
Slei

Reputation: 25

Using an static class as storage

I have a class (Class A) that has some usages and one of them is to store a variable. Then I try to set a value to this variable from Class B and to retrieve the value from Class C.

Each class is in different packages and Class A, and B are used as libraries. The problem is that when I check the value from Class C, the value is null.

How can achieve this?

Code:

Class A:

private static Config cfg;

public static void saveCFG(Config CFG) {
   cfg = CFG;
}

public static Config retrieveCFG() {
   return cfg;
}

Class B is a GUI that when a button is pressed it calls the saveCFG method:

ClassA.saveCFG(config);

And Class C has a Thread that is checking this value constantly:

final Thread t = new Thread(new Runnable() {
    @Override
    public synchronized void run() {
        while (true) {
            if (ClassA.retrieveCFG() != null) {
               System.out.println("Saved.");
            } else {
               System.out.println("Not saved.");
            }
            try {
               wait(3000);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
        }
   }
});
t.start();

Upvotes: 1

Views: 65

Answers (1)

OldCurmudgeon
OldCurmudgeon

Reputation: 65813

For cross-thread safety you should set your shared state volatile.

private volatile static Config cfg;

Upvotes: 3

Related Questions