AtomicReference的getAndSet方法异常:获取的列表始终为空
问题排查与解决方案
从你的代码来看,核心问题大概率出在LocalIpBlockingDenyListResponse类的实现上,以下是几个最可能的原因及对应解决办法:
1. 构造函数未正确赋值列表成员
你创建LocalIpBlockingDenyListResponse实例时传入了validatedDenyList,但如果类的构造函数没有把这个列表赋值给对应的成员变量,那getIpBlockingDenyList()自然返回空。
比如错误的构造函数:
public class LocalIpBlockingDenyListResponse { private List<IpBlockingDenyListRecord> ipBlockingDenyList; private int listHashCode; // 错误:遗漏列表赋值逻辑 public LocalIpBlockingDenyListResponse(List<IpBlockingDenyListRecord> list) { this.listHashCode = list.hashCode(); // 缺少 this.ipBlockingDenyList = list; } public List<IpBlockingDenyListRecord> getIpBlockingDenyList() { return ipBlockingDenyList; } }
修复方式:在构造函数中同时完成列表和哈希值的赋值:
public LocalIpBlockingDenyListResponse(List<IpBlockingDenyListRecord> list) { this.ipBlockingDenyList = list; this.listHashCode = list.hashCode(); }
2. 成员类型与传入列表类型不匹配
你提到LocalIpBlockingDenyListResponse的成员是List<CustomClass>,但更新时传入的是List<IpBlockingDenyListRecord>。如果CustomClass和IpBlockingDenyListRecord不是同一类型(也无继承/实现关系),要么编译报错,要么构造函数无法正确接收列表(比如强制类型转换导致实际赋值为空)。
修复方式:统一类型,要么把类成员改为List<IpBlockingDenyListRecord>,要么确保传入的列表是List<CustomClass>类型。
3. getIpBlockingDenyList()方法返回错误的列表
如果getIpBlockingDenyList()没有返回存储的成员列表,而是返回了一个新的空列表,那无论怎么更新都返回空。
比如错误的getter:
public List<IpBlockingDenyListRecord> getIpBlockingDenyList() { return new ArrayList<>(); // 错误:返回新空列表而非成员变量 }
修复方式:让getter返回类中存储的成员变量:
public List<IpBlockingDenyListRecord> getIpBlockingDenyList() { return this.ipBlockingDenyList; }
4. 额外验证点
- 在
setDenyListAtomicReference方法中添加日志,打印新创建的LocalIpBlockingDenyListResponse实例的列表大小,确认实例本身的列表非空:void setDenyListAtomicReference(List<IpBlockingDenyListRecord> newDenyList) { LocalIpBlockingDenyListResponse newResponse = new LocalIpBlockingDenyListResponse(newDenyList); log.info("New response list size: {}", newResponse.getIpBlockingDenyList().size()); denyListAtomicReference.set(newResponse); } - 再次确认
validate方法没有意外清空列表(虽然你说validatedDenyList非空,但可以通过日志再验证一次)。
内容的提问来源于stack exchange,提问作者LearningAsIGo
相关产品推荐
相关产品推荐

