-1

I want to develop an application where memory size should not crosses 512MB of memory space.How can I achieve that so that if memory size increases 512MB then exception has been raised to enduser to configure permgen space ?

1 Answers1

0

You'll want to use the Java Management Extensions (JMX). The linked article provides an example to set up an interactive client into this API. Specifically, the MemoryMXBean will provide access to the different JVM heaps. Here's a terse example of the bean's usage:

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.Date;
import java.util.List;

public class PermGenMonitorTask implements Runnable {
    private MemoryPoolMXBean permgenBean = null;

    public PermGenMonitorTask() {
        List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans();
        for(MemoryPoolMXBean bean : beans) {
            if(bean.getName().toLowerCase().indexOf("perm gen") >= 0) {
                permgenBean = bean;
                break;
            }
        }
    }

    @Override
    public void run() {
        MemoryUsage currentUsage = permgenBean.getUsage();
        int percentageUsed = (int)((currentUsage.getUsed() * 100)
            / currentUsage.getMax());
        System.out.println(new Date() + ": Permgen " +
            currentUsage.getUsed() +
            " of " + currentUsage.getMax() +
            " (" + percentageUsed + "%)");
    }
}
Keith
  • 3,079
  • 2
  • 17
  • 26
  • 1
    That means you're doing something wrong. Read the JMX official documentation and search the web for some examples. It's pretty straightforward once you get it working. – Keith Oct 06 '15 at 16:43