98 lines
2.6 KiB
Java
98 lines
2.6 KiB
Java
package com.qxcm.moduleutil.event;
|
|
|
|
|
|
import com.blankj.utilcode.util.GsonUtils;
|
|
|
|
import org.greenrobot.eventbus.EventBus;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
/**
|
|
* @Author $
|
|
* @Time $ $
|
|
* @Description $
|
|
*/
|
|
public class RoomGiftRunable implements Runnable {
|
|
|
|
private String data;
|
|
private static final List<MqttBean> mqttCache = new ArrayList<>();
|
|
private static final int MAX_CACHE_SIZE = 6;
|
|
private static final Object lock = new Object();
|
|
|
|
public static synchronized void addMqttCache(MqttBean mqttBean) {
|
|
if (mqttBean == null) return;
|
|
|
|
// 检查内存状态
|
|
if (isMemoryLow()) {
|
|
// 内存不足时清理缓存
|
|
clearMqttCache();
|
|
return;
|
|
}
|
|
|
|
// 限制缓存大小
|
|
if (mqttCache.size() >= MAX_CACHE_SIZE) {
|
|
mqttCache.remove(0); // 移除最旧的项
|
|
}
|
|
|
|
mqttCache.add(mqttBean);
|
|
}
|
|
|
|
public static synchronized void clearMqttCache() {
|
|
mqttCache.clear();
|
|
// 建议进行垃圾回收
|
|
// System.gc();
|
|
}
|
|
|
|
private static boolean isMemoryLow() {
|
|
Runtime runtime = Runtime.getRuntime();
|
|
long usedMemory = runtime.totalMemory() - runtime.freeMemory();
|
|
long maxMemory = runtime.maxMemory();
|
|
double memoryUsage = (double) usedMemory / maxMemory;
|
|
|
|
return memoryUsage > 0.8; // 内存使用超过80%认为是低内存
|
|
}
|
|
public RoomGiftRunable(String data) {
|
|
this.data = data;
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
MqttBean mqttBean= GsonUtils.fromJson(data, MqttBean.class);
|
|
// 线程安全地添加到缓存
|
|
synchronized (lock) {
|
|
|
|
if (mqttBean == null) return;
|
|
|
|
// 检查内存状态
|
|
if (isMemoryLow()) {
|
|
// 内存不足时清理缓存
|
|
clearMqttCache();
|
|
return;
|
|
}
|
|
|
|
// 限制缓存大小
|
|
if (mqttCache.size() >= MAX_CACHE_SIZE) {
|
|
mqttCache.remove(0); // 移除最旧的项
|
|
}
|
|
|
|
mqttCache.add(mqttBean);
|
|
// if (mqttCache.size() >= MAX_CACHE_SIZE) {
|
|
// mqttCache.remove(0); // 移除第一条数据
|
|
// }
|
|
// mqttCache.add(mqttBean); // 添加新数据
|
|
}
|
|
EventBus.getDefault().post(mqttBean);
|
|
// new FloatingWindow(CommonAppContext.getInstance(),mqttBean);
|
|
|
|
}
|
|
|
|
// 提供方法获取缓存数据
|
|
public static List<MqttBean> getMqttCache() {
|
|
synchronized (lock) {
|
|
return new ArrayList<>(mqttCache);
|
|
}
|
|
}
|
|
|
|
}
|