简体   繁体   中英

Java declare persistent static variable

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)?

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...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM