包装类返回空指针异常处理

79 阅读1分钟
@Override
public boolean tryLock(Long timeOutSec) {
    // 获取线程id
    String threadId = Thread.currentThread().getId() + "";
    //获取锁
    Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeOutSec, TimeUnit.SECONDS);
    // 防止Boolean包装类返回出现空指针异常
    return Boolean.TRUE.equals(success);
}

在代码中使用 Boolean.TRUE.equals(success) 来避免空指针异常的原因如下:


1. ​setIfAbsent() 的返回值可能为 null

  • Redis 操作异常:当 Redis 连接失败(如网络中断、服务器宕机)或命令执行异常时,setIfAbsent() 可能返回 null
  • 序列化问题:如果键或值的序列化器配置错误(例如未使用 StringRedisSerializer),可能导致命令执行失败并返回 null

2. ​直接拆箱 Boolean 会导致空指针

  • 自动拆箱陷阱:如果直接通过 success == true 或 if (success) 判断,会触发 Boolean 对象自动拆箱为 boolean 基本类型。当 success 为 null 时,拆箱操作会抛出 NullPointerException

3. ​安全比较:Boolean.TRUE.equals(success)

  • 避免空指针Boolean.TRUE 是一个非空的 Boolean 对象,调用 equals() 方法时,即使 success 为 null,也能安全返回 false 而非抛出异常

  • 代码健壮性:这种方式显式处理了 null 值场景,确保无论 success 是 truefalse 还是 null,逻辑均能正确执行。