标签:hash threadlocal 哈希算法
最近近在看java里面ThreadLocal里面对于ThreadMap的查找使用的是Hash算法,还提到了神奇数字,于是深入的看了hash这个东西,下面就来掰扯一下hash的原理,搞懂原理了,其实对于hashmap或者hashset这种类也就很好理解,无非就是算法选择的不同而已. public interface HashInterface {
/* 生成hash */
public int hash(Object value);
/* 通过hash获取对象,可以看成是寻址的过程 */
public Object get(int hash);
}public class Hash implements HashInterface {
private final Object[] tables;
public Hash1(int tablesSize) {
tables = new Object[tablesSize];
}
/*此处是其实下标,如果数组要的前几位需要被预留,则seed射为预留的个数*/
private int hashSeed = 0;
@Override
public int hash(Object value) {
if (hashSeed == tables.length - 1) {
throw new IndexOutOfBoundsException("已经超出hash范围");
}
int hash = hashSeed++;
tables[hash] = value;
return hash;
}
@Override
public Object get(int hash) {
return tables[hash];
}
} 是不是看了代码以后觉得这就是数组里面按照顺序放进去,然后返回的hash值就是数组下标嘛.基本上最简单的hash就是这样的,它的数学原型就是f(x)=a*x+b,简单吧.举这个例子,只是想说明一下hash主要是保证在规定的范围内Key对应hash值不重复,这里要注意的一个是"限定的存储(哈希表)范围",还有就是"不重复".原理就是这样的,基本上你的算法实现在hash(Object value)里面随意变换算法,只要保证在限定范围内计算出的hash是唯一的就可以了.具体可以google一下hash,有很多种实现算法.public class Hash2 implements HashInterface {
private final Object[] tables;
private int mod;
/**
* 再探测地址增量
*/
private int d;
private int hashSeed = 0;
public Hash2(int tablesSize) {
tables = new Object[tablesSize];
mod = tablesSize;
}
@Override
public int hash(Object value) {
int index = (value.hashCode() + d) % mod;
if (tables[index] != null) {
if (d == mod) {
throw new IndexOutOfBoundsException("已经超出hash范围");
}
d++;
return hash(value);
}
return index;
}
@Override
public Object get(int hash) {
return tables[hash];
}
} 这个例子里面计算hash的方式是采用取余的方式计算hash,但是不能保证每次取余的结果都不一样,比如32和52对10取余都是2,这个时候怎么办,我们增加一个增量地址,如果发现2这个hash位置上已经有值了我就把d++,看看3上面有没有值,没有的话就直接填入,并返回3为hash值.其他的避免碰撞的方法很多,如果要深入的研究的话请自己去查资料.static int HASH_INCREMENT = 0x61c88647;
static int hash = 0;
private static int nextHash() {
int i = hash;
hash = i + HASH_INCREMENT;
return i;
}
public static void main(String[] args) {
for (int j = 0; j < 4; j++) {
int size = 2 << j;
// hash = 0;
int[] indexArray = new int[size];
for (int i = 0; i < size; i++) {
indexArray[i] = nextHash() & (size - 1);
}
System.out.println(Arrays.toString(indexArray));
}
}标签:hash threadlocal 哈希算法
原文地址:http://blog.csdn.net/coffee_hc/article/details/40295903