Java Code Examples for java.lang.management.BufferPoolMXBean

The following are top voted examples for showing how to use java.lang.management.BufferPoolMXBean. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: swage   File: BufferPoolSensor.java   Source Code and License 6 votes vote down vote up
@Override
public void sense(final MetricRecorder.Context metricContext)
{
    List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);

    for (BufferPoolMXBean mxBean : pools) {
        //TODO: something else?
        String name = mxBean.getName();
        Metric countMetric = Metric.define("BufferPoolCount_"+name);
        Metric usedMetric = Metric.define("BufferPoolUsed_"+name);
        Metric maxMetric = Metric.define("BufferPoolMax_"+name);

        metricContext.record(countMetric, mxBean.getCount(), Unit.NONE);
        metricContext.record(usedMetric, mxBean.getMemoryUsed() / M, Unit.MEGABYTE);
        metricContext.record(maxMetric,  mxBean.getTotalCapacity() / M, Unit.MEGABYTE);
    }

}
 
Example 2
Project: openjdk-systemtest   File: ByteBufferMXBeanTest.java   Source Code and License 6 votes vote down vote up
public void testByteBufferMXBeanMethods() {
	List<BufferPoolMXBean> byteBufferPools = 
		ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
	
	for (int counter = 0; counter < 10; counter++) {
	
		for (BufferPoolMXBean bean: byteBufferPools) {
			
			// Name should not be blank or null
			assertNotNull ("MXBean name is null", bean.getName());
			assertFalse ("MXBean name is blank", bean.getName().equalsIgnoreCase(""));
			// Total capacity should not be negative
			assertTrue (bean.getName() + "'s total capacity was not greater than zero", bean.getTotalCapacity() >= 0);
			// Likewise memoryUsed
			assertTrue (bean.getName() + "'s memory used was not greater than zero", bean.getMemoryUsed() >= 0);
			
			assertTrue (bean.getName() + "'s object name is null or blank", 
					bean.getObjectName() != null &&	bean.getObjectName().toString() != "");
		}
	}
}
 
Example 3
Project: QDrill   File: MemoryIterator.java   Source Code and License 6 votes vote down vote up
@Override
public Object next() {
  if (!beforeFirst) {
    throw new IllegalStateException();
  }
  beforeFirst = false;
  final MemoryInfo memoryInfo = new MemoryInfo();

  final DrillbitEndpoint endpoint = context.getIdentity();
  memoryInfo.hostname = endpoint.getAddress();
  memoryInfo.user_port = endpoint.getUserPort();

  final MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  memoryInfo.heap_current = heapMemoryUsage.getUsed();
  memoryInfo.heap_max = heapMemoryUsage.getMax();

  BufferPoolMXBean directBean = getDirectBean();
  memoryInfo.jvm_direct_current = directBean.getMemoryUsed();


  memoryInfo.direct_current = context.getDrillbitContext().getAllocator().getAllocatedMemory();
  memoryInfo.direct_max = TopLevelAllocator.MAXIMUM_DIRECT_MEMORY;
  return memoryInfo;
}
 
Example 4
Project: jdk8u-jdk   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 5
Project: jdk8u-jdk   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 6
Project: openjdk-jdk10   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 7
Project: openjdk-jdk10   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 8
Project: dremio-oss   File: MemoryIterator.java   Source Code and License 6 votes vote down vote up
@Override
public Object next() {
  if (!beforeFirst) {
    throw new IllegalStateException();
  }
  beforeFirst = false;
  final MemoryInfo memoryInfo = new MemoryInfo();

  final NodeEndpoint endpoint = dbContext.getEndpoint();
  memoryInfo.hostname = endpoint.getAddress();
  memoryInfo.fabric_port = endpoint.getFabricPort();

  final MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  memoryInfo.heap_current = heapMemoryUsage.getUsed();
  memoryInfo.heap_max = heapMemoryUsage.getMax();

  BufferPoolMXBean directBean = getDirectBean();
  memoryInfo.jvm_direct_current = directBean.getMemoryUsed();


  memoryInfo.direct_current = dbContext.getAllocator().getAllocatedMemory();
  memoryInfo.direct_max = SabotConfig.getMaxDirectMemory();
  return memoryInfo;
}
 
Example 9
Project: openjdk9   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 10
Project: openjdk9   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 11
Project: jdk8u_jdk   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 12
Project: jdk8u_jdk   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 13
Project: lookaside_java-1.8.0-openjdk   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 14
Project: lookaside_java-1.8.0-openjdk   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 15
Project: antsdb   File: MemoryUtil.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool:pools) {
        System.out.println(String.format(
                "%s %d/%d", 
                pool.getName(), 
                pool.getMemoryUsed(), 
                pool.getTotalCapacity()));
    }
    RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
    for (String arg:RuntimemxBean.getInputArguments()) {
        System.out.println(arg); 
    }
    HotSpotDiagnosticMXBean hsdiag = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
    for (VMOption i:hsdiag.getDiagnosticOptions()) {
        System.out.println(i.getName() + ":" + i.getValue());
    }
    System.out.println(hsdiag.getVMOption("MaxDirectMemorySize"));
    System.out.println(sun.misc.VM.maxDirectMemory());
    System.out.println(ByteBuffer.allocateDirect(1000000000));
    System.out.println(ByteBuffer.allocateDirect(1000000000));
    System.out.println(ByteBuffer.allocateDirect(1000000000));
    System.out.println(getDirectMemoryUsed());
}
 
Example 16
Project: drill   File: MemoryIterator.java   Source Code and License 6 votes vote down vote up
@Override
public Object next() {
  if (!beforeFirst) {
    throw new IllegalStateException();
  }
  beforeFirst = false;
  final MemoryInfo memoryInfo = new MemoryInfo();

  final DrillbitEndpoint endpoint = context.getIdentity();
  memoryInfo.hostname = endpoint.getAddress();
  memoryInfo.user_port = endpoint.getUserPort();

  final MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
  memoryInfo.heap_current = heapMemoryUsage.getUsed();
  memoryInfo.heap_max = heapMemoryUsage.getMax();

  BufferPoolMXBean directBean = getDirectBean();
  memoryInfo.jvm_direct_current = directBean.getMemoryUsed();


  memoryInfo.direct_current = context.getDrillbitContext().getAllocator().getAllocatedMemory();
  memoryInfo.direct_max = DrillConfig.getMaxDirectMemory();
  return memoryInfo;
}
 
Example 17
Project: routing-bird   File: DirectBufferHealthChecker.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    try {
        long memoryUsed = 0;
        for (BufferPoolMXBean bufferPool : bufferPools) {
            if (bufferPool.getName().equals("direct")) {
                memoryUsed = bufferPool.getMemoryUsed();
            }
        }

        Counter counter = new Counter(ValueType.VALUE);
        counter.set(memoryUsed);
        check(counter, config.getDescription(), "Allocate more direct memory. ");
    } catch (Exception x) {
        // TODO what?
    }
}
 
Example 18
Project: sdcct   File: MemoryMetricSet.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, Metric> getMetrics() {
    Map<String, Metric> metrics = super.getMetrics();
    MemoryMXBean memMxBean = ManagementFactory.getMemoryMXBean();

    registerGauge(metrics, MEMORY_OBJ_PENDING_FINALIZATION_COUNT_METRIC_NAME, memMxBean.getObjectPendingFinalizationCount());

    MemoryUsage heapMemUsage = memMxBean.getHeapMemoryUsage(), nonHeapMemUsage = memMxBean.getNonHeapMemoryUsage();

    registerMemoryUsageMetrics(metrics, MEMORY_HEAP_METRIC_NAME_PREFIX, heapMemUsage);
    registerMemoryUsageMetrics(metrics, MEMORY_NON_HEAP_METRIC_NAME_PREFIX, nonHeapMemUsage);
    registerMemoryUsageMetrics(metrics, MEMORY_TOTAL_METRIC_NAME_PREFIX, (heapMemUsage.getCommitted() + nonHeapMemUsage.getCommitted()),
        (heapMemUsage.getInit() + nonHeapMemUsage.getInit()), -1, (heapMemUsage.getUsed() + nonHeapMemUsage.getUsed()),
        (heapMemUsage.getMax() + nonHeapMemUsage.getMax()));

    ManagementFactory.getMemoryPoolMXBeans().stream().filter(MemoryPoolMXBean::isValid)
        .forEach(memPoolMxBean -> registerMemoryPoolMetrics(metrics, memPoolMxBean));

    ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class).stream().forEach(bufferPoolMxBean -> registerBufferPoolMetrics(metrics, bufferPoolMxBean));

    return metrics;
}
 
Example 19
Project: infobip-open-jdk-8   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 20
Project: infobip-open-jdk-8   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 21
Project: jdk8u-dev-jdk   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 22
Project: jdk8u-dev-jdk   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 23
Project: heron   File: JVMMetrics.java   Source Code and License 6 votes vote down vote up
private void updateBufferPoolMetrics() {
  for (BufferPoolMXBean bufferPoolMXBean : bufferPoolMXBeanList) {
    String normalizedKeyName = bufferPoolMXBean.getName().replaceAll("[^\\w]", "-");

    final ByteAmount memoryUsed = ByteAmount.fromBytes(bufferPoolMXBean.getMemoryUsed());
    final ByteAmount totalCapacity = ByteAmount.fromBytes(bufferPoolMXBean.getTotalCapacity());
    final ByteAmount count = ByteAmount.fromBytes(bufferPoolMXBean.getCount());

    // The estimated memory the JVM is using for this buffer pool
    jvmBufferPoolMemoryUsage.safeScope(normalizedKeyName + "-memory-used")
        .setValue(memoryUsed.asMegabytes());

    // The estimated total capacity of the buffers in this pool
    jvmBufferPoolMemoryUsage.safeScope(normalizedKeyName + "-total-capacity")
        .setValue(totalCapacity.asMegabytes());

    // THe estimated number of buffers in this pool
    jvmBufferPoolMemoryUsage.safeScope(normalizedKeyName + "-count")
        .setValue(count.asMegabytes());
  }
}
 
Example 24
Project: jdk7-jdk   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 25
Project: tajo   File: QueryTestCaseBase.java   Source Code and License 6 votes vote down vote up
@Before
public void printTestName() {
  /* protect a travis stalled build */
  BufferPoolMXBean direct = BufferPool.getDirectBufferPool();
  BufferPoolMXBean mapped = BufferPool.getMappedBufferPool();
  System.out.println(String.format("Used heap: %s/%s, direct:%s/%s, mapped:%s/%s, Active Threads: %d, Run: %s.%s",
      FileUtil.humanReadableByteCount(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(), false),
      FileUtil.humanReadableByteCount(Runtime.getRuntime().maxMemory(), false),
      FileUtil.humanReadableByteCount(direct.getMemoryUsed(), false),
      FileUtil.humanReadableByteCount(direct.getTotalCapacity(), false),
      FileUtil.humanReadableByteCount(mapped.getMemoryUsed(), false),
      FileUtil.humanReadableByteCount(mapped.getTotalCapacity(), false),
      Thread.activeCount(),
      getClass().getSimpleName(),
      name.getMethodName()));
}
 
Example 26
Project: openjdk-source-code-learn   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 27
Project: OLD-OpenJDK8   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 28
Project: OLD-OpenJDK8   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 29
Project: JAVA_UNIT   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 30
Project: openjdk-jdk7u-jdk   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 31
Project: openjdk-jdk7u-jdk   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 32
Project: openjdk-icedtea7   File: Basic.java   Source Code and License 6 votes vote down vote up
static void check(List<BufferPoolMXBean> pools,
                  int minBufferCount,
                  long minTotalCapacity)
{
    int bufferCount = 0;
    long totalCap = 0;
    long totalMem = 0;
    for (BufferPoolMXBean pool: pools) {
        bufferCount += pool.getCount();
        totalCap += pool.getTotalCapacity();
        totalMem += pool.getMemoryUsed();
    }
    if (bufferCount < minBufferCount)
        throw new RuntimeException("Count less than expected");
    if (totalMem < minTotalCapacity)
        throw new RuntimeException("Memory usage less than expected");
    if (totalCap < minTotalCapacity)
        throw new RuntimeException("Total capacity less than expected");
}
 
Example 33
Project: openjdk-icedtea7   File: GetObjectName.java   Source Code and License 6 votes vote down vote up
static void submitTasks(ExecutorService executor, int count) {
    for (int i=0; i < count && !failed; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                List<PlatformManagedObject> mbeans = new ArrayList<>();
                mbeans.add(ManagementFactory.getPlatformMXBean(PlatformLoggingMXBean.class));
                mbeans.addAll(ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class));
                for (PlatformManagedObject pmo : mbeans) {
                    // Name should not be null
                    if (pmo.getObjectName() == null) {
                        failed = true;
                        throw new RuntimeException("TEST FAILED: getObjectName() returns null");
                    }
                }
            }
        });
    }
}
 
Example 34
Project: openjdk-systemtest   File: EchoServer.java   Source Code and License 5 votes vote down vote up
@Override
protected void heartbeat() {
	// Let them know we are alive
	// Print some stats about the ByteBuffers
	List<BufferPoolMXBean> byteBufferPools = 
		ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);

	String direct = "direct";
	String mapped = "mapped";
	
	for (BufferPoolMXBean bean: byteBufferPools) {
		if (bean.getName().equalsIgnoreCase(direct)) {
			direct += " - " + bean.getMemoryUsed() + "/" + bean.getTotalCapacity();
		}
		if (bean.getName().equalsIgnoreCase(mapped)) {
			mapped += " - " + bean.getMemoryUsed() + "/" + bean.getTotalCapacity();
		}
	}
	
	logMessage(direct + " , " + mapped);
	logMessage("Currently connected clients: " + getConnectedClients().size());
	logMessage("Total bytes received       : " + bytesReceived);
	logMessage("Total clients connected    : " + clientsConnected);
	logMessage("Total clients disconnected : " + clientsDisconnected);
	
	synchronized (connectionsPerSecond) {
		if (!connectionsPerSecond.isEmpty()) {
			logMessage("CPS Max: " + Collections.max(connectionsPerSecond.values()) );
		}
	}
	synchronized (connectionsPerMinute) {
		if (!connectionsPerMinute.isEmpty()) {
			logMessage("CPM Max: " + Collections.max(connectionsPerMinute.values()) );
		}
	}

	logMessage();
}
 
Example 35
Project: QDrill   File: MemoryIterator.java   Source Code and License 5 votes vote down vote up
private BufferPoolMXBean getDirectBean() {
  List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
  for (BufferPoolMXBean b : pools) {
    if (b.getName().equals("direct")) {
      return b;
    }
  }
  throw new IllegalStateException("Unable to find direct buffer bean.  JVM must be too old.");
}
 
Example 36
Project: QDrill   File: DrillTest.java   Source Code and License 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 37
Project: jdk8u-jdk   File: TestMaxCachedBufferSize.java   Source Code and License 5 votes vote down vote up
private static BufferPoolMXBean getDirectPool() {
    final List<BufferPoolMXBean> pools =
              ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool : pools) {
        if (pool.getName().equals("direct")) {
            return pool;
        }
    }
    throw new Error("could not find direct pool");
}
 
Example 38
Project: openjdk-jdk10   File: TestMaxCachedBufferSize.java   Source Code and License 5 votes vote down vote up
private static BufferPoolMXBean getDirectPool() {
    final List<BufferPoolMXBean> pools =
              ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool : pools) {
        if (pool.getName().equals("direct")) {
            return pool;
        }
    }
    throw new Error("could not find direct pool");
}
 
Example 39
Project: dremio-oss   File: MemoryIterator.java   Source Code and License 5 votes vote down vote up
/**
 * @return Direct buffer JMX bean
 */
public static BufferPoolMXBean getDirectBean() {
  List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
  for (BufferPoolMXBean b : pools) {
    if (b.getName().equals("direct")) {
      return b;
    }
  }
  throw new IllegalStateException("Unable to find direct buffer bean.  JVM must be too old.");
}
 
Example 40
Project: dremio-oss   File: DremioTest.java   Source Code and License 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 41
Project: openjdk9   File: TestMaxCachedBufferSize.java   Source Code and License 5 votes vote down vote up
private static BufferPoolMXBean getDirectPool() {
    final List<BufferPoolMXBean> pools =
              ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool : pools) {
        if (pool.getName().equals("direct")) {
            return pool;
        }
    }
    throw new Error("could not find direct pool");
}
 
Example 42
Project: jdk8u_jdk   File: TestMaxCachedBufferSize.java   Source Code and License 5 votes vote down vote up
private static BufferPoolMXBean getDirectPool() {
    final List<BufferPoolMXBean> pools =
              ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool : pools) {
        if (pool.getName().equals("direct")) {
            return pool;
        }
    }
    throw new Error("could not find direct pool");
}
 
Example 43
Project: lookaside_java-1.8.0-openjdk   File: TestMaxCachedBufferSize.java   Source Code and License 5 votes vote down vote up
private static BufferPoolMXBean getDirectPool() {
    final List<BufferPoolMXBean> pools =
              ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool : pools) {
        if (pool.getName().equals("direct")) {
            return pool;
        }
    }
    throw new Error("could not find direct pool");
}
 
Example 44
Project: java-bytebuffer-leak   File: DirectBBLeak.java   Source Code and License 5 votes vote down vote up
/** Returns the built-in BufferPoolMXBean for direct ByteBuffers or throws IllegalStateException. */
static private BufferPoolMXBean getDirectBean() {
  for (BufferPoolMXBean bean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
    if (bean.getName().equals("direct")) {
      return bean;
    }
  }
  throw new IllegalStateException("could not find built-in \"direct\" BufferPoolMXBean");
}
 
Example 45
Project: jmxmon   File: ProxyClient.java   Source Code and License 5 votes vote down vote up
public synchronized Collection<BufferPoolMXBean> getBufferPoolMXBeans()
      throws IOException {
String oName = "java.nio:type=BufferPool";
      // TODO: How to deal with changes to the list??
      if (bufferPoolMXBeans == null) {
          ObjectName bpName = null;
          try {
              bpName = new ObjectName(oName + ",*");
          } catch (MalformedObjectNameException e) {
              // should not reach here
              assert(false);
          }
          Set mbeans = server.queryNames(bpName, null);
          if (mbeans != null) {
          	bufferPoolMXBeans = new ArrayList<BufferPoolMXBean>();
              Iterator iterator = mbeans.iterator();
              while (iterator.hasNext()) {
                  ObjectName on = (ObjectName) iterator.next();
                  String name = oName +",name=" + on.getKeyProperty("name");

                  BufferPoolMXBean mBean =
                      newPlatformMXBeanProxy(server, name,
                      		BufferPoolMXBean.class);
                  bufferPoolMXBeans.add(mBean);
              }
          }
      }
      return bufferPoolMXBeans;
  }
 
Example 46
Project: antsdb   File: MemoryUtil.java   Source Code and License 5 votes vote down vote up
public static BufferPoolMXBean getDirectMemoryMXBean() {
    List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool:pools) {
        if (pool.getName().equals("direct")) {
            return pool;
        }
    }
    return null;
}
 
Example 47
Project: antsdb   File: MemoryUtil.java   Source Code and License 5 votes vote down vote up
public static BufferPoolMXBean getMappedMemoryMXBean() {
    List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    for (BufferPoolMXBean pool:pools) {
        if (pool.getName().equals("mapped")) {
            return pool;
        }
    }
    return null;
}
 
Example 48
Project: flink   File: MemoryLogger.java   Source Code and License 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 49
Project: flink   File: MemoryLogger.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a String with the <strong>direct</strong> memory footprint.
 *
 * <p>These stats are not part of the other memory beans.
 *
 * @param bufferPoolMxBean The direct buffer pool bean or <code>null</code> if none available.
 *
 * @return A string with the count, total capacity, and used direct memory.
 */
public static String getDirectMemoryStatsAsString(BufferPoolMXBean bufferPoolMxBean) {
	if (bufferPoolMxBean == null) {
		return "Direct memory stats: unavailable";
	}
	else {
		return String.format("Direct memory stats: Count: %d, Total Capacity: %d, Used Memory: %d",
				bufferPoolMxBean.getCount(),
				bufferPoolMxBean.getTotalCapacity(),
				bufferPoolMxBean.getMemoryUsed());
	}
}
 
Example 50
Project: drill   File: MemoryIterator.java   Source Code and License 5 votes vote down vote up
private BufferPoolMXBean getDirectBean() {
  List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
  for (BufferPoolMXBean b : pools) {
    if (b.getName().equals("direct")) {
      return b;
    }
  }
  throw new IllegalStateException("Unable to find direct buffer bean.  JVM must be too old.");
}
 
Example 51
Project: drill   File: DrillTest.java   Source Code and License 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 52
Project: sdcct   File: MemoryMetricSet.java   Source Code and License 5 votes vote down vote up
private static void registerBufferPoolMetrics(Map<String, Metric> metrics, BufferPoolMXBean bufferPoolMxBean) {
    String bufferPoolName = bufferPoolMxBean.getName(),
        bufferPoolMetricNamePrefix = buildMetricName(MEMORY_BUFFER_POOL_METRIC_NAME_PREFIX, normalizeMetricDisplayName(bufferPoolName));

    registerGauge(metrics, buildMetricName(bufferPoolMetricNamePrefix, NAME_METRIC_NAME_PART), bufferPoolName);
    registerGauge(metrics, buildMetricName(bufferPoolMetricNamePrefix, CAPACITY_METRIC_NAME_PART), bufferPoolMxBean.getTotalCapacity());
    registerGauge(metrics, buildMetricName(bufferPoolMetricNamePrefix, COUNT_METRIC_NAME_PART), bufferPoolMxBean.getCount());
    registerGauge(metrics, buildMetricName(bufferPoolMetricNamePrefix, USED_METRIC_NAME_PART), bufferPoolMxBean.getMemoryUsed());
}
 
Example 53
Project: java-bytebuffer-leak   File: DirectBBLeak.java   Source Code and License 5 votes vote down vote up
/** Returns the built-in BufferPoolMXBean for direct ByteBuffers or throws IllegalStateException. */
static private BufferPoolMXBean getDirectBean() {
  for (BufferPoolMXBean bean : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
    if (bean.getName().equals("direct")) {
      return bean;
    }
  }
  throw new IllegalStateException("could not find built-in \"direct\" BufferPoolMXBean");
}
 
Example 54
Project: tajo   File: BufferPool.java   Source Code and License 5 votes vote down vote up
/**
 * get the specified direct memory bean
 */
public static BufferPoolMXBean getDirectBufferPool() {
  for (BufferPoolMXBean pool : getBufferPools()) {
    if (pool.getName().equals("direct")) {
      return pool;
    }
  }
  return null;
}
 
Example 55
Project: tajo   File: BufferPool.java   Source Code and License 5 votes vote down vote up
/**
 * get the specified mapped memory bean
 */
public static BufferPoolMXBean getMappedBufferPool() {
  for (BufferPoolMXBean pool : getBufferPools()) {
    if (pool.getName().equals("mapped")) {
      return pool;
    }
  }
  return null;
}
 
Example 56
Project: spectator   File: BufferPoolMeter.java   Source Code and License 5 votes vote down vote up
@Override public Iterable<Measurement> measure() {
  final long timestamp = clock.wallTime();
  final BufferPoolMXBean mbean = ref.get();
  final List<Measurement> ms = new ArrayList<>();
  if (mbean != null) {
    ms.add(new Measurement(countId, timestamp, mbean.getCount()));
    ms.add(new Measurement(memoryUsedId, timestamp, mbean.getMemoryUsed()));
  }
  return ms;
}
 
Example 57
Project: jforgame   File: GameMonitor.java   Source Code and License 4 votes vote down vote up
@Override
public String printServerState() {
	final long ONE_MB = 1024 * 1024;
	String newLine = "\n";
	StringBuilder result = new StringBuilder();

	try {
		long freeMemory = Runtime.getRuntime().freeMemory() / ONE_MB;   // 空闲内存
		long totalMemory = Runtime.getRuntime().totalMemory() / ONE_MB; // 当前内存
		long maxMemory = Runtime.getRuntime().maxMemory() / ONE_MB; // 最大可使用内存
		result.append(String.format("freeMemory: %s mb", freeMemory)).append(newLine);
		result.append(String.format(String.format("usedMemory: %s mb", (totalMemory - freeMemory)))).append(newLine);
		result.append(String.format("totalMemory: %s mb", totalMemory)).append(newLine);
		result.append(String.format("maxMemory: %s mb", maxMemory)).append(newLine);

		MemoryMXBean memoryMXBean = getMemoryMXBean();
		result.append(String.format("heap memory used: %s mb", memoryMXBean.getHeapMemoryUsage().getUsed() / ONE_MB)).append(newLine);
		result.append(String.format("heap memory usage: %s", memoryMXBean.getHeapMemoryUsage())).append(newLine);
		result.append(String.format("nonHeap memory usage: %s", memoryMXBean.getNonHeapMemoryUsage())).append(newLine);

		List<BufferPoolMXBean> buffMXBeans = (List<BufferPoolMXBean>) getPlatformMXBeans(BufferPoolMXBean.class);
		for (BufferPoolMXBean buffMXBean : buffMXBeans) {
			result.append(String.format("buffer pool[%s]: used %s mb, total %s mb", buffMXBean.getName(),
						buffMXBean.getMemoryUsed() / ONE_MB, buffMXBean.getTotalCapacity() / ONE_MB)).append(newLine);
		}

		List<GarbageCollectorMXBean> gcMXBeans = getGarbageCollectorMXBeans();
		for (GarbageCollectorMXBean gcBean : gcMXBeans) {
			result.append(String.format("%s 发生 %s 次 gc, gc 总共消耗 %s 毫秒", gcBean.getName(), gcBean.getCollectionCount(), gcBean.getCollectionTime())).append(newLine);
		}

		ThreadMXBean threadMXBean = getThreadMXBean();
		int nThreadRun     = 0;
		int nThreadBlocked = 0;
		int nThreadWaiting  = 0;
		for (long threadId : threadMXBean.getAllThreadIds()) {
			ThreadInfo threadInfo = threadMXBean.getThreadInfo(threadId);
			if (threadInfo.getThreadState() == Thread.State.RUNNABLE) {
				nThreadRun++;
			}
			if (threadInfo.getThreadState() == Thread.State.BLOCKED) {
				nThreadBlocked++;
			}
			if (threadInfo.getThreadState() == Thread.State.WAITING) {
				nThreadWaiting++;
			}
		}
		result.append(String.format("活跃线程数 %s, 阻塞线程数 %s, 等待线程数 %s", nThreadRun, nThreadBlocked, nThreadWaiting)).append(newLine);

	} catch (Exception e) {
		LoggerUtils.error("", e);
	}

	return result.toString();
}
 
Example 58
Project: elasticsearch_my   File: JvmStats.java   Source Code and License 4 votes vote down vote up
public static JvmStats jvmStats() {
    MemoryUsage memUsage = memoryMXBean.getHeapMemoryUsage();
    long heapUsed = memUsage.getUsed() < 0 ? 0 : memUsage.getUsed();
    long heapCommitted = memUsage.getCommitted() < 0 ? 0 : memUsage.getCommitted();
    long heapMax = memUsage.getMax() < 0 ? 0 : memUsage.getMax();
    memUsage = memoryMXBean.getNonHeapMemoryUsage();
    long nonHeapUsed = memUsage.getUsed() < 0 ? 0 : memUsage.getUsed();
    long nonHeapCommitted = memUsage.getCommitted() < 0 ? 0 : memUsage.getCommitted();
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    List<MemoryPool> pools = new ArrayList<>();
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        try {
            MemoryUsage usage = memoryPoolMXBean.getUsage();
            MemoryUsage peakUsage = memoryPoolMXBean.getPeakUsage();
            String name = GcNames.getByMemoryPoolName(memoryPoolMXBean.getName(), null);
            if (name == null) { // if we can't resolve it, its not interesting.... (Per Gen, Code Cache)
                continue;
            }
            pools.add(new MemoryPool(name,
                    usage.getUsed() < 0 ? 0 : usage.getUsed(),
                    usage.getMax() < 0 ? 0 : usage.getMax(),
                    peakUsage.getUsed() < 0 ? 0 : peakUsage.getUsed(),
                    peakUsage.getMax() < 0 ? 0 : peakUsage.getMax()
            ));
        } catch (Exception ex) {
            /* ignore some JVMs might barf here with:
             * java.lang.InternalError: Memory Pool not found
             * we just omit the pool in that case!*/
        }
    }
    Mem mem = new Mem(heapCommitted, heapUsed, heapMax, nonHeapCommitted, nonHeapUsed, Collections.unmodifiableList(pools));
    Threads threads = new Threads(threadMXBean.getThreadCount(), threadMXBean.getPeakThreadCount());

    List<GarbageCollectorMXBean> gcMxBeans = ManagementFactory.getGarbageCollectorMXBeans();
    GarbageCollector[] collectors = new GarbageCollector[gcMxBeans.size()];
    for (int i = 0; i < collectors.length; i++) {
        GarbageCollectorMXBean gcMxBean = gcMxBeans.get(i);
        collectors[i] = new GarbageCollector(GcNames.getByGcName(gcMxBean.getName(), gcMxBean.getName()),
                gcMxBean.getCollectionCount(), gcMxBean.getCollectionTime());
    }
    GarbageCollectors garbageCollectors = new GarbageCollectors(collectors);
    List<BufferPool> bufferPoolsList = Collections.emptyList();
    try {
        List<BufferPoolMXBean> bufferPools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
        bufferPoolsList = new ArrayList<>(bufferPools.size());
        for (BufferPoolMXBean bufferPool : bufferPools) {
            bufferPoolsList.add(new BufferPool(bufferPool.getName(), bufferPool.getCount(),
                    bufferPool.getTotalCapacity(), bufferPool.getMemoryUsed()));
        }
    } catch (Exception e) {
        // buffer pools are not available
    }

    Classes classes = new Classes(classLoadingMXBean.getLoadedClassCount(), classLoadingMXBean.getTotalLoadedClassCount(),
            classLoadingMXBean.getUnloadedClassCount());

    return new JvmStats(System.currentTimeMillis(), runtimeMXBean.getUptime(), mem, threads,
            garbageCollectors, bufferPoolsList, classes);
}
 
Example 59
Project: jdk8u-jdk   File: Basic.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Random rand = new Random();

    // allocate a few direct buffers
    int bufferCount = 5 + rand.nextInt(20);
    buffers = new ArrayList<ByteBuffer>(bufferCount);
    long totalCapacity = 0L;
    for (int i=0; i<bufferCount; i++) {
        int cap = 1024 + rand.nextInt(4096);
        buffers.add( ByteBuffer.allocateDirect(cap) );
        totalCapacity += cap;
    }

    // create a mapped buffer
    Path tmpfile = Files.createTempFile("blah", null);
    tmpfile.toFile().deleteOnExit();
    try (FileChannel fc = FileChannel.open(tmpfile, READ, WRITE)) {
        mbb = fc.map(FileChannel.MapMode.READ_WRITE, 10, 100);
        bufferCount++;
        totalCapacity += mbb.capacity();
    }

    // use platform MXBeans directly
    List<BufferPoolMXBean> pools =
        ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    check(pools, bufferCount, totalCapacity);

    // use MBeanServer
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> mbeans = server.queryNames(
        new ObjectName("java.nio:type=BufferPool,*"), null);
    pools = new ArrayList<BufferPoolMXBean>();
    for (ObjectName name: mbeans) {
        BufferPoolMXBean pool = ManagementFactory
            .newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class);
        pools.add(pool);
    }
    check(pools, bufferCount, totalCapacity);

    // attempt to unmap mapped buffer
    WeakReference<MappedByteBuffer> ref = new WeakReference<>(mbb);
    mbb = null;
    do {
        System.gc();
        Thread.sleep(250);
    } while (ref.get() != null);
}
 
Example 60
Project: openjdk-jdk10   File: Basic.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Random rand = new Random();

    // allocate a few direct buffers
    int bufferCount = 5 + rand.nextInt(20);
    buffers = new ArrayList<ByteBuffer>(bufferCount);
    long totalCapacity = 0L;
    for (int i=0; i<bufferCount; i++) {
        int cap = 1024 + rand.nextInt(4096);
        buffers.add( ByteBuffer.allocateDirect(cap) );
        totalCapacity += cap;
    }

    // create a mapped buffer
    Path tmpfile = Files.createTempFile("blah", null);
    tmpfile.toFile().deleteOnExit();
    try (FileChannel fc = FileChannel.open(tmpfile, READ, WRITE)) {
        mbb = fc.map(FileChannel.MapMode.READ_WRITE, 10, 100);
        bufferCount++;
        totalCapacity += mbb.capacity();
    }

    // use platform MXBeans directly
    List<BufferPoolMXBean> pools =
        ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    check(pools, bufferCount, totalCapacity);

    // use MBeanServer
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> mbeans = server.queryNames(
        new ObjectName("java.nio:type=BufferPool,*"), null);
    pools = new ArrayList<BufferPoolMXBean>();
    for (ObjectName name: mbeans) {
        BufferPoolMXBean pool = ManagementFactory
            .newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class);
        pools.add(pool);
    }
    check(pools, bufferCount, totalCapacity);

    // attempt to unmap mapped buffer
    WeakReference<MappedByteBuffer> ref = new WeakReference<>(mbb);
    mbb = null;
    do {
        System.gc();
        Thread.sleep(250);
    } while (ref.get() != null);
}