0

I have used a static variable in a Class and I want that the value of this variable is kept unchanged after restart of the jvm. The idea is to store this value. Can someone help me ?

Im89
  • 149
  • 1
  • 10

2 Answers2

1

If you want a variable whose value can change during the execution of the code, to be restored to whatever it was when you stopped the JVM, the next time you start the JVM, then you need to persist the value to an external medium. This is typically done by storing the value in a file or database, and retrieving it the next time the program starts. A key question when solving this problem is how to represent the value outside the executing program. For simple types like numbers and strings, this is not much of an issue. For values that are objects of non-trivial classes, the problem becomes more interesting. This is known as object serialization.

With the disclaimer that there are many different ways to persist data, here is a minimal example using Java Serialization to make the point more concrete.

class MyClassData implements Serializable {

    private String myString = "A string";
    private int myNumber = 5;

    // To make the point that the state of the object stored in the 
    // variable can change at run-time.
    public void changeThings( String myString, int myNumber) {
        this.myString = myString;
        this.myNumber = myNumber;
    }
}

public class MyClass {

    private static MyClassData data = restore();

    // Call before exiting the program
    private static void store() {
        try( ObjectOutputStream out = 
            new ObjectOutputStream(new FileOutputStream("data.dat"))) {
            out.writeObject(data);
        }
        catch( IOException e ) {
            // Deal with this
        }
    }

    private static MyClassData restore() {
        try( ObjectInputStream in = 
            new ObjectInputStream(new FileInputStream("data.dat"))) {
            return (MyClassData) in.readObject();
        }
        catch( IOException | ClassNotFoundException e ) {
            return new MyClassData();
        }
    }
}
SDJ
  • 4,327
  • 1
  • 17
  • 33
0

You restart the jvm every thing will be clear.So you can't get the values from static variables. If you use database then only you get the values without failing.

Sana
  • 360
  • 3
  • 13