JAVA String源码里面的这段代码是干啥的?
阿神
阿神 2017-04-17 13:31:52
[Java讨论组]
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;
    }

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

阿神
阿神

闭关修行中......

全部回复(2)
巴扎黑

话说题主用的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.

PHPz

世界上最简单的无锁hashtable

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号