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 ?
-
2Typically you would use a relational database for this. – Tim Biegeleisen Jun 28 '19 at 10:55
-
2Simply read it from DB or persist to a file or serialize your class – Vinay Prajapati Jun 28 '19 at 10:56
-
2Use external datasource. Database, file.. – Ruslan Jun 28 '19 at 10:56
-
There is no a local storage in java for example ? – Im89 Jun 28 '19 at 11:02
-
What do you want this static variable to be @Im89 do you just want something constant, as to say when you reboot the program it will be the same value? – Luke Garrigan Jun 28 '19 at 11:03
-
@LukeGarrigan i want to keep the same value when i reboot the program – Im89 Jun 28 '19 at 11:04
-
1I suspect you are just wanting a constant, take a look at https://stackoverflow.com/questions/66066/what-is-the-best-way-to-implement-constants-in-java – Luke Garrigan Jun 28 '19 at 11:05
2 Answers
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();
}
}
}
- 4,327
- 1
- 17
- 33
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.
- 360
- 3
- 13