MATSIM
MemoryObserver.java
Go to the documentation of this file.
1 package org.matsim.utils;
2 
3 import org.apache.logging.log4j.LogManager;
4 import org.apache.logging.log4j.Logger;
5 
6 import java.util.concurrent.atomic.AtomicBoolean;
7 
11 public class MemoryObserver {
12 
13  private final static Logger LOG = LogManager.getLogger(MemoryObserver.class);
14 
15  private static Thread thread = null;
16  private static MemoryPrinter runnable = null;
17 
18  public static void start(int interval_seconds) {
19  startMillis(interval_seconds * 1000L);
20  }
21 
22  static void startMillis(long interval) {
23  stop();
24 
25  runnable = new MemoryPrinter(interval);
26  thread = new Thread(runnable, "MemoryPrinter");
27  thread.setDaemon(true);
28  thread.start();
29  }
30 
31  public static void stop() {
32  if (thread != null) {
33  runnable.stopFlag.set(true);
34  thread.interrupt();
35  }
36  }
37 
38  public static void printMemory() {
39  long totalMem = Runtime.getRuntime().totalMemory();
40  long freeMem = Runtime.getRuntime().freeMemory();
41  long usedMem = totalMem - freeMem;
42  LOG.info("used RAM: " + (usedMem/1024/1024) + " MB free: " + (freeMem/1024/1024) + " MB total: " + (totalMem/1024/1024) + " MB");
43  }
44 
45  private static class MemoryPrinter implements Runnable {
46 
47  private final long millis;
48  private final AtomicBoolean stopFlag = new AtomicBoolean(false);
49 
50  private MemoryPrinter(long millis) {
51  this.millis = millis;
52  }
53 
54  public void run() {
55  while (true) {
57 
58  try {
59  Thread.sleep(this.millis);
60  } catch (InterruptedException e) {
61  if (this.stopFlag.get()) {
62  return;
63  }
64  e.printStackTrace();
65  }
66  }
67  }
68 
69  }
70 
71 
72 }
static void start(int interval_seconds)