文档章节

关注潜在的整数越界问题 | 京东物流技术团队

京东云开发者
 京东云开发者
发布于 11/20 09:38
字数 1404
阅读 179
收藏 0

在平时的开发过程中,整数越界是一个容易被忽视的问题,关注潜在的整数越界问题可使我们编写的代码更加健壮,规避因整数越界导致的 bug。

比较器

以下是在 Code Review 中发现的比较器实现:

??

乍一看该比较器实现不存在问题,但是如果 tag1 = Integer.MIN_VALUE = -2147483648, tag2 为大于 0 的数字如 1,则此时 tag1 - tag2 = 2147483647,但是按照 java.util.Comparator#compare 的定义,tag1 小于 tag2 时,应该返回一个负数,以上写法在遇到这样的示例数据时将导致排序结果错乱,引发相关 bug。

下面看看 Spring 中比较器的实现,在 Spring 中,提供了 @Order 注解用于指定 bean 的顺序,默认值为 Ordered.LOWEST_PRECEDENCE = Integer.MAX_VALUE,即在排序时排在最后,相关源码如下:

?

??对应的比较器实现如下:

??可知其采用的 Integer.compare 方法对两个整数进行比较操作,查看 Integer#compare 方法的源码:

/**
 * Compares two {@code int} values numerically.
 * The value returned is identical to what would be returned by:
 * <pre>
 *    Integer.valueOf(x).compareTo(Integer.valueOf(y))
 * </pre>
 *
 * @param  x the first {@code int} to compare
 * @param  y the second {@code int} to compare
 * @return the value {@code 0} if {@code x == y};
 *         a value less than {@code 0} if {@code x < y}; and
 *         a value greater than {@code 0} if {@code x > y}
 * @since 1.7
 */
public static int compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

可知 java.lang.Integer#compare 并未采取 x - y 的方式进行比较,而是使用小于等于运算符直接进行比较,规避了潜在的整数越界问题。 那么文首代码正确的实现方式应为 return Integer.compare(tag1, tag2)。如果查看 JDK 中常见数值类的源码,可知均提供了静态的 compare 方法,如:java.lang.Long#compare,java.lang.Double#compare,此处不再赘述。

切量比例

??以上代码是某段业务逻辑中初始切量比例实现,取余 100 的模式常用于按比例切量、按比例降级等业务场景。以上代码使用 userPin 的哈希值取余 100 判断是否小于切量比例以决定是否执行新业务逻辑,如果我们查看 java.lang.String#hashCode 的源码实现:

/**
 * Returns a hash code for this string. The hash code for a
 * {@code String} object is computed as
 * <blockquote><pre>
 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
 * </pre></blockquote>
 * using {@code int} arithmetic, where {@code s[i]} is the
 * <i>i</i>th character of the string, {@code n} is the length of
 * the string, and {@code ^} indicates exponentiation.
 * (The hash value of the empty string is zero.)
 *
 * @return  a hash code value for this object.
 */
public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

可知 java.lang.String#hashCode 本质上是对字符串进行 s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 多项式求值,此处潜在的风险在于计算出的 hash 值可能越界,导致 userPin.hashCode() 返回值为负数,如:"jd_xxxxxxxxxxxx".hashCode() = -1406647067,且在 Java 语言中,使用负数对正数取余,是可能得到负数的。以上代码的风险在于潜在的放大了期望的切量比例,如使用以上的代码进行上线,那么当我们设定 1% 的切量比例时,会导致远超 1%的用户执行新的业务逻辑(通过采样日志发现用户 pin 集合 hashCode 值负数占比并不低),导致非预期的切量结果。

基于以上的背景,容易想到的一种修复方案为在 userPin.hashCode 外层使用 Math.abs 保证取余前的数字为正数:

??以上修复方案看似不再存在问题,但是并不能保证完全正确,我们查看 Math.abs 的源码实现:

/**
 * Returns the absolute value of an {@code int} value.
 * If the argument is not negative, the argument is returned.
 * If the argument is negative, the negation of the argument is returned.
 *
 * <p>Note that if the argument is equal to the value of
 * {@link Integer#MIN_VALUE}, the most negative representable
 * {@code int} value, the result is that same value, which is
 * negative.
 *
 * @param   a   the argument whose absolute value is to be determined
 * @return  the absolute value of the argument.
 */
public static int abs(int a) {
    return (a < 0) ? -a : a;
}

可知在注释中特意提到,如果入参是 Integer.MIN_VALUE,即 int 域中最小的值时,返回值依然为 Integer.MIN_VALUE,因为 int 域的范围为 [-2147483648, 2147483647]。如果按照 JLS 中的解释,-x equals (~x)+1。那么可知:

x = Integer.MIN_VALUE:
10000000_00000000_00000000_00000000

~x:
01111111_11111111_11111111_11111111

(~x) + 1:
10000000_00000000_00000000_00000000

如果在神灯上搜索 Math.abs,可以发现有三篇文章与该函数有关,均与 Math.abs(Integer.MIN_VALUE) 依然为 Integer.MIN_VALUE 有关。而我们在 Code Review 阶段发现该问题即从根本上规避了该问题,不会使存在 bug 的代码上线。最后切量比例修改后的实现如下:

?

总结

  • java.lang.String#hashCode 在计算过程中可能因为整数越界导致返回值为负数
  • Java 语言中的 % 是取余而不是取模,如:(-21) % 4 = (-21) - (-21) / 4 *4 = -1
  • Math.abs(int a) 当入参是 Integer.MIN_VALUE 时返回值依然是负数 Integer.MIN_VALUE

参考

?15.15.4. Unary Minus Operator -?

?What's the difference between “mod” and “remainder”? - Stack Overflow?

?Best way to make Java's modulus behave like it should with negative numbers? - Stack Overflow?

?OrderComparator.java · spring-projects/spring-framework

作者:京东物流 刘建设 张九龙 田爽

来源:京东云开发者社区 自猿其说Tech 转载请注明来源

京东云开发者
粉丝 1276
博文 1640
码字总数 4678461
作品 0
东城
私信 提问
加载中
点击引领话题?
云图说 | 图解制品仓库服务CodeArts Artifact

本文分享自华为云社区《【云图说】第277期 图解制品仓库CodeArts Artifact》,作者:阅识风云。 制品仓库服务CodeArts Artifact用于存放源码编译生成的、可运行的二进制文件,作用是实现制品...

华为云开发者联盟
47分钟前
4
0
数据资产入表在即,企业如何把握机遇,进行数据资产管理?

数据作为新时代重要的生产要素之一,数据资产化的相关工作正在提速。自今年10月1日起,中国资产评估协会制定的《数据资产评估指导意见》正式施行。同时,《企业数据资源相关会计处理暂行规定...

袋鼠云数栈
今天
5
0
揭秘网宿基于新一代QUIC协议的优化实践

近日,LiveVideoStackCon 2023音视频技术大会深圳站成功举办。流媒体应用场景日趋多样,TCP协议在弱网场景下表现不佳,而QUIC以其低延迟以及灵活的传输算法更加适用于各种网络环境下的媒体传...

LiveVideoStack
今天
3
0
即时通讯技术文集(第26期):实时音视频技术合集(Part1) [共16篇]

为了更好地分类阅读 52im.net 总计1000多篇精编文章,我将在每周三推送新的一期技术文集,本次是第26 期。 [- 1 -] 实时语音聊天中的音频处理与编码压缩技术简述 [链接] http://www.52im.net...

JackJiang-
今天
8
0
虚拟线程原理及性能分析

一、背景 JDK21 在 9 月 19 号正式发布,带来了较多亮点,其中虚拟线程备受瞩目,毫不夸张的说,它改变了高吞吐代码的编写方式,只需要小小的变动就可以让目前的 IO 密集型程序的吞吐量得到提...

得物技术
今天
54
0

没有更多内容

加载失败,请刷新页面

加载更多

{{formatHtml(o.title)}}

{{i}}-{{formatHtml(o.content)}}

{{o.author.name}}
{{o.pubDate | formatDate}}
{{o.viewCount | bigNumberTransform}}
{{o.replyCount | bigNumberTransform}}

暂无文章

便宜云服务器
登录后可查看更多优质内容
返回顶部
顶部
http://www.vxiaotou.com