p3c 分布式条件下的Integer使用"=="比较的问题

drnojrws  于 2个月前  发布在  其他
关注(0)|答案(4)|浏览(40)

开发手册中第一部份 编程规约 中第(4)部份OOP规约中第7小条中,关于“对于 Integer var = ? 在-128 至 127 之间的赋值,Integer 对象是在 IntegerCache.cache 产生,

会复用已有对象,这个区间内的 Integer 值可以直接使用==进行判断”的表述,只适用于单机程序,在分布式条件下并不能得到预期的结果。

例子,一个spark程序:

public class Constants { public static final Integer STATE = 1; }

int state = 1; Integer state1 = 1; Integer state2 = new Integer(1); Integer state3 = Integer.valueOf(1); SparkSession session = SparkSession.builder().appName("Validate").getOrCreate(); Long count = session.read().limf("/path").select("vin").map(new MapFunction<Row, String>() { @Override public String call(Row value) throws Exception { System.out.println("1 hashcode :" + System.identityHashCode(state1)+" 2:"+System.identityHashCode(state2)+" 3:"+System.identityHashCode(state3)+" constant = " + System.identityHashCode(Constants.STATE.hashCode())); System.out.println((state == Constants.STATE) + " 1:" + (state1 == Constants.STATE) + " 2:" + (state2 == Constants.STATE) + " 3:" + (state3 == Constants.STATE)); Thread.sleep(100000); return value.mkString(); } }, Encoders.STRING()) //whatever action .count();
测试结果如下:

并没有得到预期的结果

qncylg1j

qncylg1j1#

不需要这么麻烦 直接 System.out.println(new Integer(1) == new Integer(1)) 就足够说明问题了吧……

mklgxw1f

mklgxw1f2#

new Integer(1) == new Integer(1)
两块内存地址当然false

我想表达的重点是
Integer state1= 1;
Integer state2 = 1;
单机模式下state1 == state2为ture
但是上面模式下,state1和state2分属两个JVM,返回false,这种情况比较容易忽略和误用。

kqqjbcuj

kqqjbcuj3#

我司老代码就是直接比较的 == ,也是分布式,目前还没啥问题,标记一下

相关问题