GCStatsMonitor extends MBeanStatsMonitor { @Override public void handleNotification(StatisticsNotification notification) { for (StatisticId statId : notification) { StatisticDescriptor descriptor = statId.getStatisticDescriptor(); String name = descriptor.getName(); Number value; try { value = notification.getValue(statId); } catch (StatisticNotFoundException e) { value = 0; } log(name, value); if (name.equals(StatsKey.VM_GC_STATS_COLLECTIONS)) { collections.put(statId.getStatistics().getUniqueId(), value); } else if (name.equals(StatsKey.VM_GC_STATS_COLLECTION_TIME)) { collectionTime.put(statId.getStatistics().getUniqueId(), value); } } } GCStatsMonitor(String name); @VisibleForTesting  GCStatsMonitor(String name, ValueMonitor valueMonitor); @Override // this will be called multiple times initially with different collector's stats void addStatisticsToMonitor(Statistics stats); @Override Number getStatistic(String statName); @Override // this will be called each time a collector's stats changed void handleNotification(StatisticsNotification notification);  }
@Test public void handleNotification() throws Exception { StatisticsNotification notification = mock(StatisticsNotification.class); Statistics stats = mock(Statistics.class); when(stats.getUniqueId()).thenReturn(11L); StatisticId s1 = mock(StatisticId.class); when(s1.getStatistics()).thenReturn(stats); StatisticDescriptor d1 = mock(StatisticDescriptor.class); when(s1.getStatisticDescriptor()).thenReturn(d1); when(d1.getName()).thenReturn(StatsKey.VM_GC_STATS_COLLECTIONS); StatisticId s2 = mock(StatisticId.class); when(s2.getStatistics()).thenReturn(stats); StatisticDescriptor d2 = mock(StatisticDescriptor.class); when(s2.getStatisticDescriptor()).thenReturn(d2); when(d2.getName()).thenReturn(StatsKey.VM_GC_STATS_COLLECTION_TIME); List<StatisticId> list = Arrays.asList(s1, s2); when(notification.iterator()).thenReturn(list.iterator()); when(notification.getValue(s1)).thenReturn(6L); when(notification.getValue(s2)).thenReturn(100L); gcStatsMonitor.handleNotification(notification); assertThat(gcStatsMonitor.getCollections()).isEqualTo(6L); assertThat(gcStatsMonitor.getCollectionTime()).isEqualTo(100L); when(notification.getValue(s1)).thenReturn(7L); when(notification.getValue(s2)).thenReturn(200L); when(notification.iterator()).thenReturn(list.iterator()); gcStatsMonitor.handleNotification(notification); assertThat(gcStatsMonitor.getCollections()).isEqualTo(7L); assertThat(gcStatsMonitor.getCollectionTime()).isEqualTo(200L); when(stats.getUniqueId()).thenReturn(12L); when(notification.getValue(s1)).thenReturn(10L); when(notification.getValue(s2)).thenReturn(300L); when(notification.iterator()).thenReturn(list.iterator()); gcStatsMonitor.handleNotification(notification); assertThat(gcStatsMonitor.getCollections()).isEqualTo(17L); assertThat(gcStatsMonitor.getCollectionTime()).isEqualTo(500L); }