首页

关于mahout源码包中的MemoryUtil内存工具类对内存可用内存监控,监控线程管理等

标签:MemoryUtil,内存工具类,mahout     发布时间:2018-03-26   

一、前言

关于mahout源码包中org.apache.mahout.common.MemoryUtil内存工具类,对现有系统可用内存占比统计日志监控logMemoryStatistics、内存监控线程管理等。

二、源码说明

package org.apache.mahout.common;@b@@b@import java.util.concurrent.Executors;@b@import java.util.concurrent.ScheduledExecutorService;@b@import java.util.concurrent.ThreadFactory;@b@import java.util.concurrent.TimeUnit;@b@@b@import org.slf4j.Logger;@b@import org.slf4j.LoggerFactory;@b@@b@/**@b@ * Memory utilities.@b@ */@b@public final class MemoryUtil {@b@@b@  private static final Logger log = LoggerFactory.getLogger(MemoryUtil.class);@b@@b@  private MemoryUtil() {@b@  }@b@@b@  /**@b@   * Logs current heap memory statistics.@b@   *@b@   * @see Runtime@b@   */@b@  public static void logMemoryStatistics() {@b@    Runtime runtime = Runtime.getRuntime();@b@    long freeBytes = runtime.freeMemory();@b@    long maxBytes = runtime.maxMemory();@b@    long totalBytes = runtime.totalMemory();@b@    long usedBytes = totalBytes - freeBytes;@b@    log.info("Memory (bytes): {} used, {} heap, {} max", usedBytes, totalBytes,@b@             maxBytes);@b@  }@b@@b@  private static volatile ScheduledExecutorService scheduler;@b@@b@  /**@b@   * Constructs and starts a memory logger thread.@b@   *@b@   * @param rateInMillis how often memory info should be logged.@b@   */@b@  public static void startMemoryLogger(long rateInMillis) {@b@    stopMemoryLogger();@b@    scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() {@b@      private final ThreadFactory delegate = Executors.defaultThreadFactory();@b@@b@      @Override@b@      public Thread newThread(Runnable r) {@b@        Thread t = delegate.newThread(r);@b@        t.setDaemon(true);@b@        return t;@b@      }@b@    });@b@    Runnable memoryLoogerRunnable = new Runnable() {@b@      @Override@b@      public void run() {@b@        logMemoryStatistics();@b@      }@b@    };@b@    scheduler.scheduleAtFixedRate(memoryLoogerRunnable, rateInMillis, rateInMillis,@b@        TimeUnit.MILLISECONDS);@b@  }@b@@b@  /**@b@   * Constructs and starts a memory logger thread with a logging rate of 1000 milliseconds.@b@   */@b@  public static void startMemoryLogger() {@b@    startMemoryLogger(1000);@b@  }@b@@b@  /**@b@   * Stops the memory logger, if any, started via {@link #startMemoryLogger(long)} or@b@   * {@link #startMemoryLogger()}.@b@   */@b@  public static void stopMemoryLogger() {@b@    if (scheduler != null) {@b@      scheduler.shutdownNow();@b@      scheduler = null;@b@    }@b@  }@b@@b@}