首页 > JAVA String源码里面的这段代码是干啥的?

JAVA String源码里面的这段代码是干啥的?

java static {
        long nanos = System.nanoTime();
        long now = System.currentTimeMillis();
        int SEED_MATERIAL[] = {
                System.identityHashCode(String.class),
                System.identityHashCode(System.class),
                (int) (nanos >>> 32),
                (int) nanos,
                (int) (now >>> 32),
                (int) now,
                (int) (System.nanoTime() >>> 2)
        };

        // Use murmur3 to scramble the seeding material.
        // Inline implementation to avoid loading classes
        int h1 = 0;

        // body
        for (int k1 : SEED_MATERIAL) {
            k1 *= 0xcc9e2d51;
            k1 = (k1 << 15) | (k1 >>> 17);
            k1 *= 0x1b873593;

            h1 ^= k1;
            h1 = (h1 << 13) | (h1 >>> 19);
            h1 = h1 * 5 + 0xe6546b64;
        }

        // tail (always empty, as body is always 32-bit chunks)

        // finalization

        h1 ^= SEED_MATERIAL.length * 4;

        // finalization mix force all bits of a hash block to avalanche
        h1 ^= h1 >>> 16;
        h1 *= 0x85ebca6b;
        h1 ^= h1 >>> 13;
        h1 *= 0xc2b2ae35;
        h1 ^= h1 >>> 16;

        HASHING_SEED = h1;
    }

求教,这段代码是干啥的?


世界上最简单的无锁hashtable


话说题主用的jdk是什么版本的?我看了6和5都没有这样的code呢

然后翻墙去google看了下

找到了jdk更改这块儿code的说明 src/share/classes/java/lang/String.java
还有另外一段说明 Java 7 finally fixed hashing.,大概的内容贴一下

Java 7 finally fixed hashing.

java.lang.String has add a static initializer for the single purpose
of creating a HASHING_SEED. This is brand new for Java 7. The “seed
materials” used to randomize hash codes so that different JVMs don’t
have predictable hash codes are: System.currentTimeMillis and
System.nanoTime and others.

But wait, if you look at java.lang.String#hashCode() in Java 7 source
it looks identical to Java 6’s implementation! So let’s checkout
java.util.HashMap in Java 7, and we find that the hash() function
there has changed. It takes an Object instead of an int, and if the
Object is an instanceof String, then through
sun.misc.Hashing.stringHash32() it actually called a new method inside
java.lang.String#hash32(). The hash32() function passes the character
data plus the HASHING_SEED computed above to
sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length)

The Murmur3 hashing function with the hashing seed data which is based
on the time that java.lang.String’s static initializer is executed
provides excellent protection against collision attacks.

【热门文章】
【热门文章】