MST

星途 面试题库

面试题:Java WeakHashMap自定义生命周期管理与内存回收策略的实现

假设你需要自定义WeakHashMap的生命周期管理与内存回收策略,使得它能够根据特定业务需求(例如在某个时间点,或者当内存使用率达到某个阈值时)进行更精准的键值对回收,描述你的实现思路和关键代码要点。
27.2万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 监控内存使用率:使用ManagementFactory获取OperatingSystemMXBean,通过它的方法获取系统内存信息,计算内存使用率。
  2. 时间监控:利用ScheduledExecutorService定时任务来监控特定时间点。
  3. 扩展WeakHashMap:继承WeakHashMap,重写相关方法,结合上述监控逻辑,实现更精准的键值对回收。

关键代码要点

  1. 获取内存使用率
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;

public class MemoryUtil {
    public static double getMemoryUsage() {
        OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
        long totalMemory = osBean.getTotalPhysicalMemorySize();
        long freeMemory = osBean.getFreePhysicalMemorySize();
        return (1 - (double) freeMemory / totalMemory) * 100;
    }
}
  1. 定时任务
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TimeMonitor {
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    public static void startMonitoring(long initialDelay, long period, Runnable task) {
        scheduler.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
    }
}
  1. 扩展WeakHashMap
import java.util.Map;
import java.util.WeakHashMap;

public class CustomWeakHashMap<K, V> extends WeakHashMap<K, V> {
    private static final double MEMORY_THRESHOLD = 80.0; // 内存使用率阈值
    private static final long CHECK_INTERVAL = 60; // 定时检查时间间隔(秒)

    public CustomWeakHashMap() {
        startMonitoring();
    }

    private void startMonitoring() {
        TimeMonitor.startMonitoring(0, CHECK_INTERVAL, () -> {
            if (MemoryUtil.getMemoryUsage() >= MEMORY_THRESHOLD) {
                super.clear();
            }
        });
    }
}