views:

313

answers:

2

how to generate mail alerts for the following changes in jvm

1)memory 2) threads 3)db connections

by using jmx

any help would be useful

thanks

+1  A: 

I'll answer your question re: memory. To get a notification any time a given memory pool, exceeds a threshhold, do something like the below. To get a list of all the memory pools, call ManagementFactory.getMemoryPoolMXBeans(). Then choose the (ones) that matter for you. One my machine, the list is:

Code Cache
Eden Space
Survivor Space
Tenured Gen
Perm Gen
Perm Gen [shared-ro]
Perm Gen [shared-rw]

but I think there is deliberately no standard on this and they vary between versions and implementations. So first get a pool you're interested in:

MemoryPoolMXBean memPool = ...; // Get a MemoryPoolMXBean

Then, check if a usage threshold is allowed. If so, set one (in bytes)

if(memPool.isUsageThresholdSupported())
{
  memPool.setUsageThreshold(5000000);
}

Then, request notifications when the threshhold is exceeded, by passing a NotificationListener to the addNotificationListener of a MemoryMXBean (actually, you have to cast it to NotificationEmitter first). In the example, the NotificationListener is an anonymous inner class, but it can be whatever you want, as long as it implements the javax.management.NotificationListener interface. Basically, what I've done below is print stupid messages to stdout/stderr, depending on how much memory is being used. Of course, you can hook into JavaMail or a third-party mail framework to send a mail instead.

NotificationEmitter memBean = (NotificationEmitter)(ManagementFactory.getMemoryMXBean());
memBean.addNotificationListener(new NotificationListener()
{
  public void handleNotification(Notification n, Object handback)
  {
    CompositeData cd = (CompositeData)n.getUserData();
    MemoryNotificationInfo mni = MemoryNotificationInfo.from(cd);
    MemoryUsage memUsage = mni.getUsage();
    long bytesUsed = memUsage.getUsed();
    if(bytesUsed > 512000000)
      System.err.println("Oh, no, we're using more than 512M!");
    else
      System.out.println("It's okay.  We're only using " + bytesUsed + " bytes.");
  }
}

As far as threads, the relevant bean is obviously ThreadMXBean, which you get from ManagementFactory.getThreadMXBean(). But it doesn't look like there's a built-in way to set a threshhold or add listeners, so you'll have to poll. You can get thread count from just ManagementFactory.getThreadMXBean().getAllThreadIds().length , and of course, there's more information available in the bean.

Finally, "db connections" is just vague. What database system are you using? Is the JVM in question the server or client, etc.

I recommend you ask a new question if you need more info on the latter two resources.

Matthew Flaschen
A: 

thanks mr Matthew Flaschen

your answer is very useful. i will ask new question for dbconnections

thanks

Suresh

Sunny Mate