private double calcAverageWithinPeriod(VirtualMachineStatisticsChangedEvent event) {

    if (event.getStatistics().isNA()) {
      return -1;
    }

    final String key = event.getVirtualMachine().getUid();
    movingAverageStatistics.addStatistics(key, event.getStatistics().getMemoryHeapUsedPerc());
    double average = movingAverageStatistics.getAverageAndReset(key);

    if (average != -1 && logger.isLoggable(Level.FINE)) {
      logger.fine(
          "vm pid=["
              + event.getVirtualMachine().getDetails().getPid()
              + "] memory used=["
              + event.getStatistics().getMemoryHeapUsedPerc()
              + "%]"
              + " average=["
              + average
              + "%] values: "
              + movingAverageStatistics.toString(key));
    }

    return average;
  }
 @Override
 public void destroy() throws Exception {
   movingAverageStatistics.clear();
   admin.getVirtualMachines().getVirtualMachineRemoved().remove(this);
   admin.getVirtualMachines().getVirtualMachineStatisticsChanged().remove(this);
   admin.getVirtualMachines().stopStatisticsMonitor();
 }
  @Override
  public void virtualMachineRemoved(VirtualMachine virtualMachine) {

    movingAverageStatistics.clear(virtualMachine.getUid());

    final String groupUid = generateGroupUid(virtualMachine.getUid());
    Alert[] alertsByGroupUid =
        ((InternalAlertManager) admin.getAlertManager())
            .getAlertRepository()
            .getAlertsByGroupUid(groupUid);
    if (alertsByGroupUid.length != 0 && !alertsByGroupUid[0].getStatus().isResolved()) {
      AlertFactory factory = new AlertFactory();
      factory.name(ALERT_NAME);
      factory.groupUid(groupUid);
      factory.description(
          AlertBeanUtils.getGridComponentShortName(virtualMachine)
              + " Heap memory is unavailable; JVM has been removed");
      factory.severity(AlertSeverity.WARNING);
      factory.status(AlertStatus.NA);
      factory.componentUid(virtualMachine.getUid());
      factory.componentDescription(AlertBeanUtils.getGridComponentDescription(virtualMachine));
      factory.config(config.getProperties());

      Alert alert = factory.toAlert();
      admin.getAlertManager().triggerAlert(new HeapMemoryUtilizationAlert(alert));
    }
  }