如何保证Hash值为非负数?

346 阅读1分钟

public class HashPartitioner<K2, V2> implements Partitioner<K2, V2> {
    public HashPartitioner() {
    }
 
    public void configure(JobConf job) {
    }
 
    public int getPartition(K2 key, V2 value, int numReduceTasks) {
        return (key.hashCode() & 2147483647) % numReduceTasks;
    }
}

在mapreduce中 分区过程中通过类HashPartitioner<K,V> implements Partitioner<K,V> 来实现相同的key 的value 会分配到同一个reduceTask中

HashPartitioner 类就是负责处理分配的类

(key.hashCode() & 2147483647) % numReduceTasks

hasCode()是返回一个哈希值,hashCode()源码是:

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;
   

返回值是int类型,Integer.MIN_VALUE=2147483647 转换成二进制值是1111111111111111111111111111111, 符号位为0, key.hashCode() & 2147483647 可以保证结果是非负数,HashPartitioner类返回的int值就是一个逻辑的分区数值

注意,不要用 Maths.abs(key.hashCode()) 取 hash值,原因是 当 key.hashCode() 值为 Interger.MIN_VALUE时候,依旧为负数。