search

Home  >  Q&A  >  body text

java - ThreadLocal 中两行代码的理解

AndroidThreadLocal代码中看到了两行代码:

    private static AtomicInteger hashCounter = new AtomicInteger(0);

    private final int hash = hashCounter.getAndAdd(0x61c88647 * 2);

对于这两行代码个人理解不好,问题在于对于同一个ThreadLocal实例,既然hashfinal修饰了,那么它的值应该是固定的,而且第一个实例的hash变量应该为0才对。这个理解对吗?

但是个人调试了下,发现这个对于同一个ThreadLocal实例,这个值有可能发生变化(我是在使用set函数然后在断点打进去看的)。另外,这个值应该是用于计算散列码,这么写不会有问题么?

黄舟黄舟2766 days ago607

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-18 09:25:06

    Since the variable hash is final, once it is assigned a value, its value will not change thereafter.

    Since the value of hash depends on hashCounter, the value of hash may be different, depending on whether hashCounter has called a method similar to increment, add or set before assigning a value to hash.

    reply
    0
  • Cancelreply