简体   繁体   中英

Java timer class does not auto refresh a Runtime function?

I have this timer function written in java.

    import java.util.Timer;  //Libraries used
    import java.util.TimerTask;

    public static void main(String[] args) {
    Timer clock = new Timer();
    clock.schedule(new TimerTask() {
          @Override
          public void run() {
              System.out.println(Runtime.getRuntime().freeMemory());

          }
        }, 1*1*1000, 1*1*1000);// One second intervals
       }

I get this as a result(in bits):

115224312

113179200

113179200

...Same number(113179200)...forever

I want this function to auto refresh and change the number, but it does not do that. And I am unsure why. I have tried other methods(loops, other timers, etc.), but those do not work either.

I updated your code with some memory use after you start the timer check:

public static void main(String[] args) {
    Timer clock = new Timer();
    clock.schedule(new TimerTask() {
          @Override
          public void run() {
              System.out.print("Total: " + Runtime.getRuntime().totalMemory());
              System.out.println(" Free: " + Runtime.getRuntime().freeMemory());

          }
        }, 1*1*1000, 1*1*1000);// One second intervals

    // now use memory
    ArrayList<Object> arrays = new ArrayList<>();
    for (int i = 0; i < 1_000_000; ++i) {
        ArrayList<String> strings = new ArrayList<>();
        for (int j = 0; j < 1_000_000; ++j) {
            strings.add("" + j);
        }
        arrays.add(strings);
    }
    System.out.println("Loop complete");
}

And here's some of the output:

Total: 1203240960 Free: 752378848
Total: 1785200640 Free: 1107948136
Total: 3265265664 Free: 1522323408
Total: 3642228736 Free: 1180813496
Total: 5323096064 Free: 1982845016
Total: 5456265216 Free: 1627489984
Total: 7387742208 Free: 2923462928
Total: 7571767296 Free: 2455798264
Total: 7579631616 Free: 1657495280

As you can see, the amount of free memory (as well as total memory) is changing.

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