Пример #1
0
  /**
   * Silly Microbenchmark
   *
   * @throws CryptoException
   */
  public void testBenchmark() throws CryptoException {
    System.out.println("BigInteger encoding benchmarks:");
    final int ITERATIONS = 100000;
    final Runtime runtime = Runtime.getRuntime();
    long start = System.currentTimeMillis();
    long memstart = runtime.freeMemory();
    for (int i = 0; i < ITERATIONS; i++) {
      final String encoded = Base32.encode(TESTSTRINGS[i % TESTSTRINGS.length]);
      assertEquals("TESTSTRINGS[" + i + "]", TYLER_OUTPUT[i % TESTSTRINGS.length], encoded);
    }
    long dur = System.currentTimeMillis() - start;
    long memuse = memstart - runtime.freeMemory();
    System.out.println(ITERATIONS + " iterations took: " + dur + "ms");
    System.out.println(ITERATIONS + " iterations used: " + memuse + " bytes");
    /*
            System.out.println("\nWaterken encoding benchmarks:");
            start=System.currentTimeMillis();
            memstart=runtime.freeMemory();
            for (int i=0;i<ITERATIONS;i++){
                final String encoded = com.waterken.url.Base32.encode(TESTSTRINGS[i%TESTSTRINGS.length].getBytes());
                assertEquals("TESTSTRINGS["+i+"]",TYLER_OUTPUT[i%TESTSTRINGS.length],encoded);
            }
            dur=System.currentTimeMillis()-start;
            memuse=memstart-runtime.freeMemory();
            System.out.println(ITERATIONS+" iterations took: "+dur+"ms");
            System.out.println(ITERATIONS+" iterations used: "+memuse+" bytes");
    */

  }
  public static ServerInfoFormMap memory(Sigar sigar) {
    ServerInfoFormMap monitorMap = new ServerInfoFormMap();
    try {
      Runtime r = Runtime.getRuntime();
      monitorMap.put("jvmTotal", Common.div(r.totalMemory(), (1024 * 1024), 2) + "M"); // java总内存
      monitorMap.put(
          "jvmUse",
          Common.div(r.totalMemory() - r.freeMemory(), (1024 * 1024), 2) + "M"); // JVM使用内存
      monitorMap.put("jvmFree", Common.div(r.freeMemory(), (1024 * 1024), 2) + "M"); // JVM剩余内存
      monitorMap.put(
          "jvmUsage", Common.div(r.totalMemory() - r.freeMemory(), r.totalMemory(), 2)); // JVM使用率

      Mem mem = sigar.getMem();
      // 内存总量
      monitorMap.put("ramTotal", Common.div(mem.getTotal(), (1024 * 1024 * 1024), 2) + "G"); // 内存总量
      monitorMap.put("ramUse", Common.div(mem.getUsed(), (1024 * 1024 * 1024), 2) + "G"); // 当前内存使用量
      monitorMap.put(
          "ramFree", Common.div(mem.getFree(), (1024 * 1024 * 1024), 2) + "G"); // 当前内存剩余量
      monitorMap.put("ramUsage", Common.div(mem.getUsed(), mem.getTotal(), 2)); // 内存使用率

      Swap swap = sigar.getSwap();
      // 交换区总量
      monitorMap.put("swapTotal", Common.div(swap.getTotal(), (1024 * 1024 * 1024), 2) + "G");
      // 当前交换区使用量
      monitorMap.put("swapUse", Common.div(swap.getUsed(), (1024 * 1024 * 1024), 2) + "G");
      // 当前交换区剩余量
      monitorMap.put("swapFree", Common.div(swap.getFree(), (1024 * 1024 * 1024), 2) + "G");
      monitorMap.put("swapUsage", Common.div(swap.getUsed(), swap.getTotal(), 2)); //

    } catch (Exception e) {
    }
    return monitorMap;
  }
Пример #3
0
  /**
   * Action used for forcing garbage collection. If WOCachingEnabled is true (we take this to mean
   * that the application is in production) you need to give a password to access it.<br>
   * <br>
   * Synopsis:<br>
   * pw=<i>aPassword</i> <br>
   * Form Values:<br>
   * <b>pw</b> password to be checked against the system property <code>er.extensions.ERXGCPassword
   * </code>. <br>
   *
   * @return short info about free and used memory before and after GC.
   */
  public WOActionResults forceGCAction() {
    if (canPerformActionWithPasswordKey("er.extensions.ERXGCPassword")) {
      ERXStringHolder result = pageWithName(ERXStringHolder.class);
      Runtime runtime = Runtime.getRuntime();
      ERXUnitAwareDecimalFormat decimalFormatter =
          new ERXUnitAwareDecimalFormat(ERXUnitAwareDecimalFormat.BYTE);
      decimalFormatter.setMaximumFractionDigits(2);

      String info = "Before: ";
      info += decimalFormatter.format(runtime.maxMemory()) + " max, ";
      info += decimalFormatter.format(runtime.totalMemory()) + " total, ";
      info += decimalFormatter.format(runtime.totalMemory() - runtime.freeMemory()) + " used, ";
      info += decimalFormatter.format(runtime.freeMemory()) + " free\n";

      int count = 5;
      if (request().stringFormValueForKey("count") != null) {
        count = Integer.parseInt(request().stringFormValueForKey("count"));
      }
      ERXExtensions.forceGC(count);

      info += "After: ";
      info += decimalFormatter.format(runtime.maxMemory()) + " max, ";
      info += decimalFormatter.format(runtime.totalMemory()) + " total, ";
      info += decimalFormatter.format(runtime.totalMemory() - runtime.freeMemory()) + " used, ";
      info += decimalFormatter.format(runtime.freeMemory()) + " free\n";

      result.setValue(info);
      log.info("GC forced\n" + info);
      return result;
    }
    return forbiddenResponse();
  }
  public void run(HttpSession session) {
    Runtime runtime = Runtime.getRuntime();

    NumberFormat nf = NumberFormat.getInstance();

    if (_log.isDebugEnabled()) {
      _log.debug(
          "Before:\t\t"
              + nf.format(runtime.freeMemory())
              + "\t"
              + nf.format(runtime.totalMemory())
              + "\t"
              + nf.format(runtime.maxMemory()));
    }

    System.gc();

    if (_log.isDebugEnabled()) {
      _log.debug(
          "After:\t\t"
              + nf.format(runtime.freeMemory())
              + "\t"
              + nf.format(runtime.totalMemory())
              + "\t"
              + nf.format(runtime.maxMemory()));
    }
  }
Пример #5
0
  public BenchPerformance(String fileName, Graph graph) {
    r = Runtime.getRuntime();
    forceGC();
    long used1 = r.totalMemory() - r.freeMemory();
    g = graph;
    try {
      g.read(fileName);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
    System.out.println(
        "Graph read: " + g.getNodeCount() + " nodes and " + g.getEdgeCount() + " edges");

    for (Node n : g) n.clearAttributes();
    for (Edge e : g.getEachEdge()) e.clearAttributes();
    forceGC();
    long used2 = r.totalMemory() - r.freeMemory();
    measureValues = new EnumMap<Measures, Long>(Measures.class);
    measureValues.put(Measures.MEMORY, used2 - used1);

    nodeIds = new ArrayList<String>(g.getNodeCount());
    for (Node n : g) nodeIds.add(n.getId());
    // sort them to be sure that we always work with the same nodes
    Collections.sort(nodeIds);

    edgeIds = new ArrayList<String>(g.getEdgeCount());
    for (Edge e : g.getEachEdge()) edgeIds.add(e.getId());
    Collections.sort(edgeIds);
  }
Пример #6
0
  public static void main(String args[]) {
    Runtime r = Runtime.getRuntime();
    long mem1, mem2;
    Integer someints[] = new Integer[1000];

    System.out.println("Total memory is: " + r.totalMemory());
    mem1 = r.freeMemory();
    System.out.println("Initial free memory: " + mem1);
    r.gc();
    mem1 = r.freeMemory();
    System.out.println("Free memory after garbage collection: " + mem1);

    for (int i = 0; i < 1000; i++) someints[i] = new Integer(i); // allocate integers

    mem2 = r.freeMemory();
    System.out.println("Free memory after allocation: " + mem2);
    System.out.println("Memory used by allocation: " + (mem1 - mem2));

    // discard Integers
    for (int i = 0; i < 1000; i++) someints[i] = null;

    mem2 = r.freeMemory();
    System.out.println("Free memory after discarding Integers: " + mem2);

    r.gc(); // request garbage collection

    mem2 = r.freeMemory();
    System.out.println("Free memory after collecting discarded Integers: " + mem2);
  }
Пример #7
0
 private long computeFreeMemory() {
   Runtime runtime = Runtime.getRuntime();
   long maxMemory = runtime.maxMemory();
   long usedMemory = runtime.totalMemory() - runtime.freeMemory();
   long potentiallyFreeMemory =
       (maxMemory == Long.MAX_VALUE ? runtime.freeMemory() : maxMemory - usedMemory);
   return potentiallyFreeMemory;
 }
Пример #8
0
 /**
  * We were having issues with heap usage going over on many runs, so we added this for
  * convenience. If you're running in to heap errors as well, adjust the hadoop settings for heap
  * memory allocation.
  */
 public static void print_heap_usage() {
   int mb = 1024 * 1024;
   Runtime instance = Runtime.getRuntime();
   System.out.println("***** Heap utilization statistics [MB] *****");
   System.out.printf("Total Memory: %d\n", instance.totalMemory() / mb);
   System.out.printf("Free Memory: %d\n", instance.freeMemory() / mb);
   System.out.printf("Used Memory: %d\n", (instance.totalMemory() - instance.freeMemory()) / mb);
   System.out.printf("Max Memory: %d\n", instance.maxMemory() / mb);
 }
Пример #9
0
  /**
   * Create the JVM information
   *
   * @return
   */
  private JsonValue getJVMInformation() {
    JsonObject report = JsonValueBuilder.jsonValue();

    // Arguments
    List<String> arguments = runtimeMxBean.getInputArguments();
    JsonArray argumentsJson = report.array(JVM_ARGUMENTS_LABEL);
    for (String argument : arguments) {
      argumentsJson.add(argument);
    }

    // some useful jvm properties
    JsonObject propertiesJson = JsonValueBuilder.jsonValue();

    propertiesJson.put("java.vm.info", System.getProperty("java.vm.info"));
    propertiesJson.put("java.vm.name", System.getProperty("java.vm.info"));
    propertiesJson.put(
        "java.vm.specification.name", System.getProperty("java.vm.specification.name"));
    propertiesJson.put(
        "java.vm.specification.vendor", System.getProperty("java.vm.specification.vendor"));
    propertiesJson.put(
        "java.vm.specification.version", System.getProperty("java.vm.specification.version"));
    propertiesJson.put("java.vm.vendor", System.getProperty("java.vm.vendor"));
    propertiesJson.put("java.vm.version", System.getProperty("java.vm.version"));

    report.put(JVM_PROPERTIES_LABEL, propertiesJson.build().asMap());

    report.put(JVM_JAVA_VERSION_LABEL, System.getProperty("java.version"));

    // Memory
    JsonObject memoryJson = JsonValueBuilder.jsonValue();
    memoryJson.put(JVM_UNIT_MEMORY_LABEL, FileSizeUnit.MB);

    // Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    // Print used memory
    memoryJson.put(
        JVM_USED_MEMORY_LABEL, FileSizeUnit.B.toMB(runtime.totalMemory() - runtime.freeMemory()));

    // Print free memory
    memoryJson.put(JVM_FREE_MEMORY_LABEL, FileSizeUnit.B.toMB(runtime.freeMemory()));

    // Print total available memory
    memoryJson.put(JVM_TOTAL_MEMORY_LABEL, FileSizeUnit.B.toMB(runtime.totalMemory()));

    // Print Maximum available memory
    memoryJson.put(JVM_MAX_MEMORY_LABEL, FileSizeUnit.B.toMB(runtime.maxMemory()));

    // GNU systems don't support the "sun.arch.data.model" property, so we print both
    memoryJson.put(JVM_BIT_SIZE_GNU_LABEL, System.getProperty("sun.arch.data.model"));
    memoryJson.put(JVM_BIT_SIZE_LABEL, System.getProperty("os.arch"));

    report.put(JVM_MEMORY_LABEL, memoryJson.build().asMap());

    return report.build();
  }
Пример #10
0
 public static void betweenBenchmarks() throws InterruptedException {
   if (executeGcBetween) {
     Runtime runtime = Runtime.getRuntime();
     System.out.println("freeMemory before gc: " + runtime.freeMemory());
     System.gc();
     System.out.println("Sleeping a while...");
     Thread.sleep(1000); // give the gc a chance to kick in.
     System.out.println("freeMemory after gc : " + runtime.freeMemory());
   }
 }
Пример #11
0
 public void EndPerfMeasure() {
   Runtime r = Runtime.getRuntime();
   long nextmem = r.totalMemory() - r.freeMemory();
   long usedmem = nextmem - OriginalMemory;
   r.gc();
   nextmem = r.totalMemory() - r.freeMemory();
   long finalmem = nextmem - OriginalMemory;
   TemporaryMemoryUsed = usedmem - finalmem;
   MemoryNeeded = finalmem;
   ProcessingTime = System.currentTimeMillis() - StartTime;
 }
Пример #12
0
 public static String reportMem() {
   Runtime r = Runtime.getRuntime();
   r.gc();
   return "used: "
       + ((r.totalMemory() - r.freeMemory()) / 1024L)
       + "kB (free: "
       + r.freeMemory()
       + " of "
       + r.totalMemory()
       + ")";
 }
Пример #13
0
 public static String getMemoryInformation() {
   Runtime rt = Runtime.getRuntime();
   DecimalFormat df = new DecimalFormat("###,###,###,###");
   return "used = "
       + df.format(rt.totalMemory() - rt.freeMemory())
       + " free = "
       + rt.freeMemory()
       + " total = "
       + rt.totalMemory()
       + " max = "
       + rt.maxMemory();
 }
Пример #14
0
  @SuppressWarnings("deprecation")
  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (cmd.getName().equalsIgnoreCase("check-server")) {

      Player _user = (Player) sender;

      if (_user.hasPermission(PERM.ADMINKA_DATA_CMD)) {

        Runtime runtime = Runtime.getRuntime();

        System.gc();

        String nameOS = System.getProperty("os.name");

        sender.sendMessage("§a§l§m=============================================");
        sender.sendMessage("");
        sender.sendMessage(
            "§8▍  §3RAM §8▏ ➲ §7USED §8/ §7TOTAL §8/ §7FREE "
                + ChatColor.AQUA
                + (runtime.totalMemory() - runtime.freeMemory()) / 1048576L
                + " MB / "
                + runtime.totalMemory() / 1048576L
                + " MB / "
                + runtime.freeMemory() / 1048576L
                + " MB");

        sender.sendMessage(
            "§8▍  §3CPU §8▏ ➲ §7Available (cores) "
                + ChatColor.AQUA
                + Runtime.getRuntime().availableProcessors());

        sender.sendMessage(
            "§8▍  §3CPU §8▏ ➲ §7Architecture "
                + ChatColor.BLUE
                + System.getenv("PROCESSOR_ARCHITECTURE"));

        sender.sendMessage("§8▍  §3OS §8▏ ➲   " + ChatColor.LIGHT_PURPLE + nameOS);

        sender.sendMessage("");
        sender.sendMessage("§a§l§m=============================================");

        sender.sendMessage(
            plugin.getConfig().getString("Config.Spravy.Prefix").replace('&', '§')
                + "Tento plugin napísal » §9 Shiro");

        _user.playSound(_user.getLocation(), Sound.CHICKEN_EGG_POP, 1.0F, 2.0F);
        _user.playEffect(_user.getLocation(), Effect.FIREWORKS_SPARK, 1);
      }
    }
    return false;
  }
Пример #15
0
 private long measureMemoryUse() throws InterruptedException {
   long total;
   long freeAfter;
   long freeBefore;
   Runtime runtime = Runtime.getRuntime();
   do {
     total = runtime.totalMemory();
     freeBefore = runtime.freeMemory();
     System.gc();
     Thread.sleep(100);
     freeAfter = runtime.freeMemory();
   } while (total != runtime.totalMemory() || freeAfter > freeBefore);
   return total - freeAfter;
 }
Пример #16
0
  /**
   * Calculate the amount of memory used by calling obj's method
   *
   * @param obj the instance of caller
   * @param method the method to be called
   * @param args the arguments to be passed for this method
   * @return How much memory is used by calling obj's method (in KByte)
   * @throws Exception
   */
  public static double memory(Object obj, Method method, Object... args) throws Exception {
    double mem = 0.0;
    Runtime runtime = Runtime.getRuntime();
    double start, end;

    start = runtime.freeMemory();
    method.invoke(obj, args);
    end = runtime.freeMemory();

    mem = end - start;
    mem /= 1000.0;

    return mem;
  }
Пример #17
0
  public void run() {

    Runtime rt = Runtime.getRuntime();
    while (keepAlive) {
      try {
        memStats.update(rt.totalMemory(), rt.freeMemory(), rt.maxMemory());
        Thread.sleep(sleepTime);
      } catch (InterruptedException ie) {
        keepAlive = false;
      }
    }

    memStats.update(rt.totalMemory(), rt.freeMemory(), rt.maxMemory());
  }
Пример #18
0
    @Override
    public void notifyWriteSpillBegin(Spillable spillable, int spillSize, String spillReason) {
      int numFiles = spillable.spillCount();

      if (numFiles % 10 == 0) {
        LOG.info(
            "spilling group: {}, on grouping: {}, num times: {}, with reason: {}",
            new Object[] {
              joinField.printVerbose(), spillable.getGrouping().print(), numFiles + 1, spillReason
            });

        Runtime runtime = Runtime.getRuntime();
        long freeMem = runtime.freeMemory() / 1024 / 1024;
        long maxMem = runtime.maxMemory() / 1024 / 1024;
        long totalMem = runtime.totalMemory() / 1024 / 1024;

        LOG.info(
            "mem on spill (mb), free: " + freeMem + ", total: " + totalMem + ", max: " + maxMem);
      }

      LOG.info("spilling {} tuples in list to file number {}", spillSize, numFiles + 1);

      flowProcess.increment(Spill.Num_Spills_Written, 1);
      flowProcess.increment(Spill.Num_Tuples_Spilled, spillSize);
    }
Пример #19
0
  private void logStats(MavenSession session) {
    logger.info(chars('-', LINE_LENGTH));

    Date finish = new Date();

    long time = finish.getTime() - session.getRequest().getStartTime().getTime();

    String wallClock = session.getRequest().isThreadConfigurationPresent() ? " (Wall Clock)" : "";

    logger.info("Total time: " + getFormattedTime(time) + wallClock);

    logger.info("Finished at: " + finish);

    System.gc();

    Runtime r = Runtime.getRuntime();

    long MB = 1024 * 1024;

    logger.info(
        "Final Memory: "
            + (r.totalMemory() - r.freeMemory()) / MB
            + "M/"
            + r.totalMemory() / MB
            + "M");
  }
Пример #20
0
  /**
   * 返回服务系统信息
   *
   * @throws Exception
   */
  public static ServerStatus getServerStatus() throws Exception {
    ServerStatus status = new ServerStatus();
    status.setServerTime(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));
    status.setServerName(System.getenv().get("COMPUTERNAME"));

    Runtime rt = Runtime.getRuntime();
    // status.setIp(InetAddress.getLocalHost().getHostAddress());
    status.setJvmTotalMem(rt.totalMemory() / (1024 * 1024));
    status.setJvmFreeMem(rt.freeMemory() / (1024 * 1024));
    status.setJvmMaxMem(rt.maxMemory() / (1024 * 1024));
    Properties props = System.getProperties();
    status.setServerOs(
        props.getProperty("os.name")
            + " "
            + props.getProperty("os.arch")
            + " "
            + props.getProperty("os.version"));
    status.setJavaHome(props.getProperty("java.home"));
    status.setJavaVersion(props.getProperty("java.version"));
    status.setJavaTmpPath(props.getProperty("java.io.tmpdir"));

    Sigar sigar = new Sigar();
    getServerCpuInfo(sigar, status);
    getServerDiskInfo(sigar, status);
    getServerMemoryInfo(sigar, status);

    return status;
  }
Пример #21
0
  public static void main(String[] args) {
    int i = 0, j;
    String arg;
    char flag;
    boolean vflag = false;
    String outputfile = "";
    int d = -1, t = -1, b = -1, l = -1, r = -1;

    while (i < args.length) {

      if (args[i].startsWith("-")) {
        arg = args[i++];
        for (j = 1; j < arg.length(); j++) {
          flag = arg.charAt(j);
          switch (flag) {
            case 'd':
              d = Integer.valueOf(args[i++]);
              break;
            case 't':
              t = Integer.valueOf(args[i++]);
              break;
            case 'b':
              b = Integer.valueOf(args[i++]);
              break;
            case 'l':
              l = Integer.valueOf(args[i++]);
              break;
            case 'r':
              r = Integer.valueOf(args[i++]);
              break;
            default:
              System.err.println("ParseCmdLine: illegal option " + flag);
              break;
          }
        }
      }
    }
    if (d < 0 || t < 0 || l < 0 || r < 0) {
      System.out.println("Invalid number of arguements.");
      System.out.println("Proper usage: java Tpdahp.Demo -d # -l # -r # -t # -b #");
    } else {

      long start = System.currentTimeMillis();

      // Instanciate and calls the Simulator
      DiffusionSimulator simulator = new DiffusionSimulator(d, t, b, l, r);
      simulator.simulate();

      long end = System.currentTimeMillis();
      simulator.printResults();

      Runtime runtime = Runtime.getRuntime();
      long memory = runtime.totalMemory() - runtime.freeMemory();
      System.out.println(String.format("\n\nPerformance Summary: "));
      System.out.println(String.format(" - Time Taken: %dms", end - start));
      System.out.println(String.format(" - Memory Used: %d bytes", memory));
      System.out.println(
          String.format(" - Number of iteration: %d", simulator.getNumberOfIterations()));
    }
  }
Пример #22
0
    public ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView("systeminfo");
        mav.addObject("sysprops", new TreeMap<String, String>((Map) System.getProperties()));
        mav.addObject("sysenv", new TreeMap<String, String>((Map) System.getenv()));
        mav.addObject("systime", new Date());

        //Calculate app uptime duration
        Date appStartTime = (Date) getServletContext().getAttribute("appStartTime");
        long durationMillis = new Date().getTime() - appStartTime.getTime();
        String duration = DurationFormatUtils.formatDurationWords(durationMillis, true, false);
        mav.addObject("appUptime", duration);

        //Calculate system resources.
        Runtime runtime = Runtime.getRuntime();
        long totalMem = runtime.totalMemory() / MB;
        long freeMem = runtime.freeMemory() / MB;
        long avaCPU = runtime.availableProcessors();
        mav.addObject("sysres", "CPU: " + avaCPU + ", MemoryUsed: " + (totalMem - freeMem) + "M/" + totalMem + "M");
        
        if(applicationProperties== null){
            applicationProperties = new Properties();
        }
        mav.addObject("applicationProps", applicationProperties);
        
        return mav;
    }
Пример #23
0
  private static Date initSDGcomputation(Config cfg) throws FileNotFoundException {
    if (cfg == null || !cfg.requiredFieldsSet()) {
      throw new IllegalArgumentException("Configuration is not valid: " + cfg);
    }

    File outputDir = new File(cfg.outputDir);
    if (!outputDir.exists()) {
      outputDir.mkdir();
    }

    Log.setLogFile(cfg.logFile);
    if (cfg.logLevel != null) {
      Log.setMinLogLevel(cfg.logLevel);
    }

    Date date = new Date();
    Log.info("Starting Analysis at " + date);

    boolean assertions = false;
    assert (assertions = true);
    Log.info("Assertions are turned " + (assertions ? "ON" : "OFF"));
    Log.info("Java Datamodel: " + System.getProperty("sun.arch.data.model") + "bit");
    Runtime run = Runtime.getRuntime();
    Log.info("Avaliable Processors: " + run.availableProcessors());
    Log.info("Free Memory: " + run.freeMemory());
    Log.info("Total Memory: " + run.totalMemory());
    Log.info("Maximum Memory: " + run.maxMemory());
    Log.info(Debug.getSettings());

    Log.info("SDGFactory.getSDG started with: \n" + cfg);

    return date;
  }
Пример #24
0
 public static void main(String[] args) {
   Runtime rt = Runtime.getRuntime();
   System.out.println("处理器数量:" + rt.availableProcessors());
   System.out.println("空闲内存数:" + rt.freeMemory());
   System.out.println("总内存数:" + rt.totalMemory());
   System.out.println("可用最大内存数:" + rt.maxMemory());
 }
Пример #25
0
  private boolean checkAvaliableMemory(int neededMemory, TestResult testResult) {
    if ((ourMode & CHECK_MEMORY) == 0) return true;

    boolean possibleOutOfMemoryError = possibleOutOfMemory(neededMemory);
    if (possibleOutOfMemoryError) {
      tryGc(5);
      possibleOutOfMemoryError = possibleOutOfMemory(neededMemory);
      if (possibleOutOfMemoryError) {
        log("OutOfMemoryError: dumping memory");
        Runtime runtime = Runtime.getRuntime();
        long total = runtime.totalMemory();
        long free = runtime.freeMemory();
        String errorMessage =
            "Too much memory used. Total: "
                + total
                + " free: "
                + free
                + " used: "
                + (total - free)
                + "\n";
        addErrorMessage(testResult, errorMessage);
      }
    }
    return !possibleOutOfMemoryError;
  }
Пример #26
0
 public void getJvmInfo() {
   Map<String, String> result = new HashMap<String, String>();
   // 内存
   Runtime runtime = Runtime.getRuntime();
   double max = runtime.maxMemory() * 1.0 / 1024.0 / 1024.0;
   result.put("maxMemory", max + "");
   double total = runtime.totalMemory() * 1.0 / 1024.0 / 1024.0;
   result.put("totalMemory", total + "");
   double freeMemory = runtime.freeMemory() * 1.0 / 1024.0 / 1024.0;
   result.put("freeMemory", freeMemory + "");
   // 线程
   ThreadGroup group = Thread.currentThread().getThreadGroup();
   ThreadGroup topGroup = group;
   // 遍历线程组树,获取根线程组
   while (group != null) {
     topGroup = group;
     group = group.getParent();
   }
   // 激活的线程数加倍
   int estimatedSize = topGroup.activeCount() * 2;
   Thread[] slackList = new Thread[estimatedSize];
   // 获取根线程组的所有线程
   int actualSize = topGroup.enumerate(slackList);
   // copy into a list that is the exact size
   Thread[] list = new Thread[actualSize];
   System.arraycopy(slackList, 0, list, 0, actualSize);
   for (int i = 0; i < list.length; i++) {
     // System.out.println(list[i].getName());
   }
   result.put("thread", list.length + "");
   String resultStr = JsonUtil.map2Json(result);
   this.print(resultStr);
 }
Пример #27
0
  /**
   * 获取当前 jvm 的内存信息
   *
   * @return
   */
  public static String toMemoryInfo() {

    Runtime currRuntime = Runtime.getRuntime();
    int nFreeMemory = (int) (currRuntime.freeMemory() / 1024 / 1024);
    int nTotalMemory = (int) (currRuntime.totalMemory() / 1024 / 1024);
    return nFreeMemory + "M/" + nTotalMemory + "M(free/total)";
  }
Пример #28
0
  @Override
  public void mousePressed(final MouseEvent e) {
    Performance.gc(3);
    repaint();

    final Runtime rt = Runtime.getRuntime();
    final long max = rt.maxMemory();
    final long total = rt.totalMemory();
    final long used = total - rt.freeMemory();

    final String inf =
        TOTAL_MEM_C
            + Performance.format(max, true)
            + NL
            + RESERVED_MEM_C
            + Performance.format(total, true)
            + NL
            + MEMUSED_C
            + Performance.format(used, true)
            + NL
            + NL
            + H_USED_MEM;

    BaseXDialog.info(gui, inf);
  }
Пример #29
0
  /** @return a human friendly string for the VM used memory */
  private String formatUsedMemory() {
    final Runtime runtime = Runtime.getRuntime();
    final long usedBytes = runtime.totalMemory() - runtime.freeMemory();
    String formattedUsedMemory = formatMemory(usedBytes);

    return formattedUsedMemory;
  }
Пример #30
0
  @Override
  public void getInfo(PrintWriter pw) {
    pw.append(" CellDomainName   = ").println(getCellDomainName());
    pw.format(
        " I/O rcv=%d;asw=%d;frw=%d;rpy=%d;exc=%d\n",
        _packetsReceived, _packetsAnswered, _packetsForwarded, _packetsReplied, _exceptionCounter);
    long fm = _runtime.freeMemory();
    long tm = _runtime.totalMemory();

    pw.format(" Memory : tot=%d;free=%d;used=%d\n", tm, fm, tm - fm);
    pw.println(" Cells (Threads)");
    for (String name : _nucleus.getCellNames()) {
      pw.append(" ").append(name).append("(");
      Thread[] threads = _nucleus.getThreads(name);
      if (threads != null) {
        boolean first = true;
        for (Thread thread : threads) {
          pw.print(thread.getName());
          if (first) {
            first = false;
          } else {
            pw.print(",");
          }
        }
      }
      pw.println(")");
    }
  }