Reputation: 6595
I have a class and I need to create a unique counter within that, something like that:
public class Foo {
private static int FOO_COUNT = 0
public static getNextCount(){
return ++FOO_COUNT;
}
//... more methods...
}
The counter value has to be persistent between Java VM restarts, app re-deployment etc, so that provides continuous counter throughout application life-cycle.
How (and if) that could be achieved (preferably without resorting to the DB or similar persistence mechanisms)?
Upvotes: 1
Views: 860
Reputation: 2708
You need to serialize your object and after you can save it localy like this for example :
import java.io.*;
public class SerializeDemo {
public static void main(String [] args) {
private static int FOO_COUNT = 0;
try {
FileOutputStream fileOut =
new FileOutputStream("/tmp/save.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(FOO_COUNT);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/save.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
public class Foo implements java.io.Serializable {
private static int FOO_COUNT = 0
public static getNextCount(){
return ++FOO_COUNT;
}
//... more methods...
}
Upvotes: 2