Why design ThreadLocalMap as static nest class in ThreadLocal?

Why design ThreadLocalMap as Static Class in ThreadLocal ? While static and non-static nested classes have differences below.

  • Nested static class doesn't need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.

  • Inner class(or non-static nested class) can access both static and non-static members of Outer class. A static class cannot access non-static members of the Outer class. It can access only static members of Outer class.

  • An instance of Inner class cannot be created without an instance of outer class and an Inner class can reference data and methods defined in Outer class in which it nests, so we don't need to pass reference of an object to the constructor of the Inner class. For this reason Inner classes can make program simple and concise.


  • First it should be noted that ThreadLocalMap is a package-private class, thus it's not a part of the API, but an implementation detail which may change in future JDK versions if necessary.

    Why it's not non-static? Just because non-static nested class (inner class) is bound to the concrete instance of the outer class. In our case it should be bound to the concrete ThreadLocal variable. This is just wrong: ThreadLocalMap is bounded to the thread and stores all the values of all ThreadLocal variables for given thread. Thus binding it to the concrete ThreadLocal instance is meaningless.

    Maybe it looks more logical to make ThreadLocalMap the inner class of the Thread class. However ThreadLocalMap just does not need the Thread object to operate, so this would just add some unnecessary overhead. The reason it's located inside the ThreadLocal class is that the ThreadLocal is responsible for ThreadLocalMap creation. ThreadLocalMap is created for current thread only when the first ThreadLocal is set in this thread, but after that the same ThreadLocalMap is used for all other ThreadLocal variables.

    Another alternative would be to hold ThreadLocalMap as separate package-private class in java.lang package. Nothing wrong with such option: it's just a matter of taste and depends on what developers want more: to group related functionality in single source file or to keep source file length smaller.

    链接地址: http://www.djcxy.com/p/92004.html

    上一篇: 不能使用封闭的类型实例

    下一篇: 为什么在ThreadLocal中将ThreadLocalMap设计为静态嵌套类?