内存不足—在java中发生内存不足时,如何使用notificationlistener正确获取通知

cs7cruho  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(254)

我需要知道是否有outofmemory发生,我添加了下面的代码到我的程序。但它不能正常工作。有什么问题吗?

ManagementFactory.getMemoryPoolMXBeans().stream()
    .filter(pool -> pool.getType() == MemoryType.HEAP)
    .filter(MemoryPoolMXBean::isUsageThresholdSupported)
    .forEach(memoryPoolMXBean -> {
      double threshold = 0.85;
      MemoryUsage usage = memoryPoolMXBean.getUsage();
      memoryPoolMXBean.setCollectionUsageThreshold((int) Math.floor(usage.getMax() * threshold));
    });

NotificationEmitter notificationEmitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
notificationEmitter.addNotificationListener((notification, handback) -> {
  if (MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED.equals(notification.getType()))
  {
    // Log, send an alert or whatever makes sense in your situation
    System.err.println("Running low on memory");
  }
}, null, null);

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题