Java Code Examples for java.lang.management.ManagementFactory#getMemoryMXBean()

The following examples show how to use java.lang.management.ManagementFactory#getMemoryMXBean() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MemoryImpl.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
static void createNotification(String notifType,
                               String poolName,
                               MemoryUsage usage,
                               long count) {
    MemoryImpl mbean = (MemoryImpl) ManagementFactory.getMemoryMXBean();
    if (!mbean.hasListeners()) {
        // if no listener is registered.
        return;
    }
    long timestamp = System.currentTimeMillis();
    String msg = getNotifMsg(notifType);
    Notification notif = new Notification(notifType,
                                          mbean.getObjectName(),
                                          getNextSeqNumber(),
                                          timestamp,
                                          msg);
    MemoryNotificationInfo info =
        new MemoryNotificationInfo(poolName,
                                   usage,
                                   count);
    CompositeData cd =
        MemoryNotifInfoCompositeData.toCompositeData(info);
    notif.setUserData(cd);
    mbean.sendNotification(notif);
}
 
Example 2
Source File: GarbageCollectorMonitor.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
/**
 *  JVM memory snapshot
 **/
@Override
public MemoryStat memSnapshot() {
    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean() ;
    MemoryUsage heap = memBean.getHeapMemoryUsage();
    MemoryUsage nonHeap = memBean.getNonHeapMemoryUsage();
    MemoryStat stat=new MemoryStat();
    // heap
    stat.setHeapMax(heap.getMax());
    stat.setHeapInit(heap.getInit());
    stat.setHeapCommitted(heap.getCommitted());
    stat.setHeapUsed(heap.getUsed());
    // non-heap
    stat.setNonHeapInit(nonHeap.getInit());
    stat.setNonHeapMax(nonHeap.getMax());
    stat.setNonHeapUsed(nonHeap.getUsed());
    stat.setNonHeapCommitted(nonHeap.getCommitted());

    // allocated by ByteBuffer.allocateDirect()
    stat.setDirectBufferSize(SharedSecrets.getJavaNioAccess().getDirectBufferPool().getMemoryUsed());

    return stat;
}
 
Example 3
Source File: PlatformMBeanResourceUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testMemoryMXBean() throws IOException {
    DescribedResource describedResource = basicResourceTest("memory", null);

    MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    boolean verbose = describedResource.resource.get("verbose").asBoolean();
    Assert.assertEquals(mbean.isVerbose(), verbose);

    ModelNode op = getOperation("write-attribute", "memory", null);
    op.get("name").set("verbose");
    op.get("value").set(!verbose);
    executeOp(op, false);
    Assert.assertEquals(mbean.isVerbose(), !verbose);

    // Restore
    mbean.setVerbose(verbose);

    op = getOperation("gc", "memory", null);
    Assert.assertFalse(executeOp(op, false).isDefined());
}
 
Example 4
Source File: MemoryImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static void createNotification(String notifType,
                               String poolName,
                               MemoryUsage usage,
                               long count) {
    MemoryImpl mbean = (MemoryImpl) ManagementFactory.getMemoryMXBean();
    if (!mbean.hasListeners()) {
        // if no listener is registered.
        return;
    }
    long timestamp = System.currentTimeMillis();
    String msg = getNotifMsg(notifType);
    Notification notif = new Notification(notifType,
                                          mbean.getObjectName(),
                                          getNextSeqNumber(),
                                          timestamp,
                                          msg);
    MemoryNotificationInfo info =
        new MemoryNotificationInfo(poolName,
                                   usage,
                                   count);
    CompositeData cd =
        MemoryNotifInfoCompositeData.toCompositeData(info);
    notif.setUserData(cd);
    mbean.sendNotification(notif);
}
 
Example 5
Source File: ClusterStatus.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * @param numDecommissionedNodes number of decommission trackers
 */
ClusterStatus(int trackers, int blacklists, long ttExpiryInterval, 
              int maps, int reduces, int maxMaps, int maxReduces, 
              JobTracker.State state, int numDecommissionedNodes) {
  numActiveTrackers = trackers;
  numBlacklistedTrackers = blacklists;
  this.numExcludedNodes = numDecommissionedNodes;
  this.ttExpiryInterval = ttExpiryInterval;
  map_tasks = maps;
  reduce_tasks = reduces;
  max_map_tasks = maxMaps;
  max_reduce_tasks = maxReduces;
  this.state = state;

  MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage status = memoryMXBean.getHeapMemoryUsage();
  used_memory = status.getUsed();
  max_memory = status.getMax();
}
 
Example 6
Source File: StatusResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@Inject
public StatusResource(NodeVersion nodeVersion, NodeInfo nodeInfo, ServerConfig serverConfig, LocalMemoryManager memoryManager)
{
    this.nodeInfo = requireNonNull(nodeInfo, "nodeInfo is null");
    this.version = requireNonNull(nodeVersion, "nodeVersion is null");
    this.environment = requireNonNull(nodeInfo, "nodeInfo is null").getEnvironment();
    this.coordinator = requireNonNull(serverConfig, "serverConfig is null").isCoordinator();
    this.memoryManager = requireNonNull(memoryManager, "memoryManager is null");
    this.memoryMXBean = ManagementFactory.getMemoryMXBean();
    this.logicalCores = Runtime.getRuntime().availableProcessors();

    if (ManagementFactory.getOperatingSystemMXBean() instanceof OperatingSystemMXBean) {
        // we want the com.sun.management sub-interface of java.lang.management.OperatingSystemMXBean
        this.operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    }
}
 
Example 7
Source File: JvmMetrics.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
private void doMemoryUpdates() {
    MemoryMXBean memoryMXBean =
           ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap =
            memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap =
            memoryMXBean.getHeapMemoryUsage();
    metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed()/M);
    metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted()/M);
    metrics.setMetric("memHeapUsedM", memHeap.getUsed()/M);
    metrics.setMetric("memHeapCommittedM", memHeap.getCommitted()/M);
}
 
Example 8
Source File: MemoryLogger.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new memory logger that logs in the given interval and lives until the
 * given termination future completes.
 *
 * @param logger The logger to use for outputting the memory statistics.
 * @param interval The interval in which the thread logs.
 * @param monitored termination future for the system to whose life the thread is bound. The thread terminates
 *                  once the system terminates.
 */
public MemoryLogger(Logger logger, long interval, CompletableFuture<Void> monitored) {
	super("Memory Logger");
	setDaemon(true);
	setPriority(Thread.MIN_PRIORITY);
	
	this.logger = logger;
	this.interval = interval;
	this.monitored = monitored;

	this.memoryBean = ManagementFactory.getMemoryMXBean();
	this.poolBeans = ManagementFactory.getMemoryPoolMXBeans();
	this.gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

	// The direct buffer pool bean needs to be accessed via the bean server
	MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
	BufferPoolMXBean directBufferBean = null;
	try {
		directBufferBean = ManagementFactory.newPlatformMXBeanProxy(
				beanServer,
				"java.nio:type=BufferPool,name=direct",
				BufferPoolMXBean.class);
	}
	catch (Exception e) {
		logger.warn("Failed to initialize direct buffer pool bean.", e);
	}
	finally {
		this.directBufferBean = directBufferBean;
	}
}
 
Example 9
Source File: MemoryLogger.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new memory logger that logs in the given interval and lives as long as the
 * given actor system.
 *
 * @param logger The logger to use for outputting the memory statistics.
 * @param interval The interval in which the thread logs.
 * @param monitored The actor system to whose life the thread is bound. The thread terminates
 *                  once the actor system terminates.
 */
public MemoryLogger(Logger logger, long interval, ActorSystem monitored) {
	super("Memory Logger");
	setDaemon(true);
	setPriority(Thread.MIN_PRIORITY);
	
	this.logger = logger;
	this.interval = interval;
	this.monitored = monitored;

	this.memoryBean = ManagementFactory.getMemoryMXBean();
	this.poolBeans = ManagementFactory.getMemoryPoolMXBeans();
	this.gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

	// The direct buffer pool bean needs to be accessed via the bean server
	MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
	BufferPoolMXBean directBufferBean = null;
	try {
		directBufferBean = ManagementFactory.newPlatformMXBeanProxy(
				beanServer,
				"java.nio:type=BufferPool,name=direct",
				BufferPoolMXBean.class);
	}
	catch (Exception e) {
		logger.warn("Failed to initialize direct buffer pool bean.", e);
	}
	finally {
		this.directBufferBean = directBufferBean;
	}
}
 
Example 10
Source File: ServerWatch.java    From ping with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void initialize() {
    this.initializeStartTime();
    this.memoryMxBean = ManagementFactory.getMemoryMXBean();
    this.heapUsageAtStartTime = this.memoryMxBean.getHeapMemoryUsage();

}
 
Example 11
Source File: DremioTest.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public SystemManager(){
  memoryBean = ManagementFactory.getMemoryMXBean();
  BufferPoolMXBean localBean = null;
  List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
  for(BufferPoolMXBean b : pools){
    if(b.getName().equals("direct")){
      localBean = b;

    }
  }
  directBean = localBean;
}
 
Example 12
Source File: ServerWatch.java    From ping with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void initialize() {
    this.initializeStartTime();
    this.memoryMxBean = ManagementFactory.getMemoryMXBean();
    this.heapUsageAtStartTime = this.memoryMxBean.getHeapMemoryUsage();

}
 
Example 13
Source File: BuildServer.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
private static void checkMemory() {
  MemoryMXBean mBean = ManagementFactory.getMemoryMXBean();
  mBean.gc();
  LOG.info("Build " + buildCount + " current used memory: "
    + mBean.getHeapMemoryUsage().getUsed() + " bytes");
}
 
Example 14
Source File: MemoryMonitorTest.java    From pitest with Apache License 2.0 4 votes vote down vote up
@Test
public void dumpMemoryInfo() {
  try {
    System.out.println("\nDUMPING MEMORY INFO\n");
    // Read MemoryMXBean
    final MemoryMXBean memorymbean = ManagementFactory.getMemoryMXBean();
    System.out.println("Heap Memory Usage: "
        + memorymbean.getHeapMemoryUsage());
    System.out.println("Non-Heap Memory Usage: "
        + memorymbean.getNonHeapMemoryUsage());

    // Read Garbage Collection information
    final List<GarbageCollectorMXBean> gcmbeans = ManagementFactory
        .getGarbageCollectorMXBeans();
    for (final GarbageCollectorMXBean gcmbean : gcmbeans) {
      System.out.println("\nName: " + gcmbean.getName());
      System.out.println("Collection count: " + gcmbean.getCollectionCount());
      System.out.println("Collection time: " + gcmbean.getCollectionTime());
      System.out.println("Memory Pools: ");
      final String[] memoryPoolNames = gcmbean.getMemoryPoolNames();
      for (final String memoryPoolName : memoryPoolNames) {
        System.out.println("\t" + memoryPoolName);
      }
    }

    // Read Memory Pool Information
    System.out.println("Memory Pools Info");
    final List<MemoryPoolMXBean> mempoolsmbeans = ManagementFactory
        .getMemoryPoolMXBeans();
    for (final MemoryPoolMXBean mempoolmbean : mempoolsmbeans) {
      System.out.println("\nName: " + mempoolmbean.getName());
      System.out.println("Usage: " + mempoolmbean.getUsage());
      System.out.println("Collection Usage: "
          + mempoolmbean.getCollectionUsage());
      System.out.println("Peak Usage: " + mempoolmbean.getPeakUsage());
      System.out.println("Type: " + mempoolmbean.getType());
      System.out.println("Memory Manager Names: ");
      final String[] memManagerNames = mempoolmbean.getMemoryManagerNames();
      for (final String memManagerName : memManagerNames) {
        System.out.println("\t" + memManagerName);
      }
      System.out.println("\n");
    }
  } catch (final Exception e) {
    e.printStackTrace();
  }
}
 
Example 15
Source File: MemoryPools.java    From opentelemetry-java with Apache License 2.0 4 votes vote down vote up
/** Constructs a new module that is capable to export metrics about "jvm_memory". */
public MemoryPools() {
  this.memoryBean = ManagementFactory.getMemoryMXBean();
  this.poolBeans = ManagementFactory.getMemoryPoolMXBeans();
  this.meter = OpenTelemetry.getMeter("jvm_memory");
}
 
Example 16
Source File: MemoryUsageGaugeSet.java    From semantic-metrics with Apache License 2.0 4 votes vote down vote up
public MemoryUsageGaugeSet() {
    this(ManagementFactory.getMemoryMXBean(), ManagementFactory.getMemoryPoolMXBeans());
}
 
Example 17
Source File: ExtractorUtils.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static int getNumberOfThreads (List<ServerInfo> serverInfoList, List<DiskStoreImpl> diskStores) {
  /****
   * As we extract one diskstore at a time for a given server. 
   * Here the logic is we find the largest disk-store and use its size as a basis for worst case heap memory required 
   * for salvaging a server at a given time.
   * This helps in determining how may servers can we salvage in parallel for given heap memory.
   * This is a very conservative estimate. 
   */
  long maxDiskStoreSizeOnDisk = 0;
  int maxNumberOfServersInParallel = 1;
  final double mbDiv = Math.pow(1024, 2);

  for (ServerInfo serverInfo : serverInfoList) {
    long maxDiskStoreSizeForServer = ExtractorUtils.getMaxDiskStoreSizeForServer(serverInfo, diskStores);
    if (maxDiskStoreSizeOnDisk < maxDiskStoreSizeForServer) {
      maxDiskStoreSizeOnDisk = maxDiskStoreSizeForServer;
    }
  }

  GemFireXDDataExtractorImpl.logInfo("Maximum disk-store size on disk " + maxDiskStoreSizeOnDisk/mbDiv + " MB");
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage heapMemUsage = memBean.getHeapMemoryUsage();
  long usedMemory = heapMemUsage.getUsed();
  long committedMemory = heapMemUsage.getCommitted();

  //For safety using the committedMemory for calculation, as it is the memory that is guaranteed to be available for the VM. 
  long availableMemory = (committedMemory - usedMemory);
  GemFireXDDataExtractorImpl.logInfo("Available memory : " + availableMemory/mbDiv + " MB");

  double maxMemoryPerServer = (1.2)*maxDiskStoreSizeOnDisk;

  //Setting the lower limit
  if (maxMemoryPerServer < 1) {
    maxMemoryPerServer = 1;
  }

  GemFireXDDataExtractorImpl.logInfo("Estimated memory needed per server : " + maxMemoryPerServer/mbDiv + " MB");

  if (availableMemory < maxMemoryPerServer) {
    GemFireXDDataExtractorImpl.logWarning("Not enough memory to extract the server, extractor could possibly run out of memory");
  }

  maxNumberOfServersInParallel =  (int) (availableMemory/maxMemoryPerServer);

  if (maxNumberOfServersInParallel < 1) {
    maxNumberOfServersInParallel = 1;
  }

  GemFireXDDataExtractorImpl.logInfo("Recommended number of threads to extract server(s) in parallel : " + maxNumberOfServersInParallel);
  return maxNumberOfServersInParallel;
}
 
Example 18
Source File: ExtractorUtils.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static int getNumberOfThreads (List<ServerInfo> serverInfoList, List<DiskStoreImpl> diskStores) {
  /****
   * As we extract one diskstore at a time for a given server. 
   * Here the logic is we find the largest disk-store and use its size as a basis for worst case heap memory required 
   * for salvaging a server at a given time.
   * This helps in determining how may servers can we salvage in parallel for given heap memory.
   * This is a very conservative estimate. 
   */
  long maxDiskStoreSizeOnDisk = 0;
  int maxNumberOfServersInParallel = 1;
  final double mbDiv = Math.pow(1024, 2);

  for (ServerInfo serverInfo : serverInfoList) {
    long maxDiskStoreSizeForServer = ExtractorUtils.getMaxDiskStoreSizeForServer(serverInfo, diskStores);
    if (maxDiskStoreSizeOnDisk < maxDiskStoreSizeForServer) {
      maxDiskStoreSizeOnDisk = maxDiskStoreSizeForServer;
    }
  }

  GemFireXDDataExtractorImpl.logInfo("Maximum disk-store size on disk " + maxDiskStoreSizeOnDisk/mbDiv + " MB");
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  MemoryUsage heapMemUsage = memBean.getHeapMemoryUsage();
  long usedMemory = heapMemUsage.getUsed();
  long committedMemory = heapMemUsage.getCommitted();

  //For safety using the committedMemory for calculation, as it is the memory that is guaranteed to be available for the VM. 
  long availableMemory = (committedMemory - usedMemory);
  GemFireXDDataExtractorImpl.logInfo("Available memory : " + availableMemory/mbDiv + " MB");

  double maxMemoryPerServer = (1.2)*maxDiskStoreSizeOnDisk;

  //Setting the lower limit
  if (maxMemoryPerServer < 1) {
    maxMemoryPerServer = 1;
  }

  GemFireXDDataExtractorImpl.logInfo("Estimated memory needed per server : " + maxMemoryPerServer/mbDiv + " MB");

  if (availableMemory < maxMemoryPerServer) {
    GemFireXDDataExtractorImpl.logWarning("Not enough memory to extract the server, extractor could possibly run out of memory");
  }

  maxNumberOfServersInParallel =  (int) (availableMemory/maxMemoryPerServer);

  if (maxNumberOfServersInParallel < 1) {
    maxNumberOfServersInParallel = 1;
  }

  GemFireXDDataExtractorImpl.logInfo("Recommended number of threads to extract server(s) in parallel : " + maxNumberOfServersInParallel);
  return maxNumberOfServersInParallel;
}
 
Example 19
Source File: JVM_MANAGEMENT_MIB_IMPL.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Instantiate a JVM MIB intrusmentation.
 * A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
 * <CODE>NotificationEmitter</CODE>
 */
public JVM_MANAGEMENT_MIB_IMPL() {
    handler = new NotificationHandler();
    emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
    emitter.addNotificationListener(handler, null, null);
}
 
Example 20
Source File: InfoItemUtils.java    From bazel with Apache License 2.0 4 votes vote down vote up
static MemoryUsage getMemoryUsage() {
  MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  return memBean.getHeapMemoryUsage();
}