- jdk的ThreadLocal: ThreadLocalMap 是用数组来维护的,类似HashMap。如果ThreadLocal对象的hash碰撞则使用开放式地址法来解决碰撞问题
- 当碰撞情况比较多的时候,set get的速度是一个一个接着找 查找速度 O(n)
- FastThreadLocal 存放的容器 InternalThreadLocalMap是
private static Object[] newIndexedVariableTable() { Object[] array = new Object[32]; Arrays.fill(array, UNSET); return array; } - 但每个FastThreadLocal创建的时候,都会包含一个序号的属性。这个序号就是存放数组里面的序号;
- 这个序号的产生是由
//FastThreadLocal 的部分代码 private final int index; public FastThreadLocal() { index = InternalThreadLocalMap.nextVariableIndex(); } // InternalThreadLocalMap 部分代码 public static int nextVariableIndex() { int index = nextIndex.getAndIncrement(); if (index < 0) { nextIndex.decrementAndGet(); throw new IllegalStateException("too many thread-local indexed variables"); } return index; } static final AtomicInteger nextIndex = new AtomicInteger(); - FastThreadLocal的速度优势主要集中在同一线程,操作多个ThreadLocal的时候
Netty的FastThreadLocal速度 优化
最新推荐文章于 2024-08-14 12:24:01 发布
本文深入探讨了JDK中ThreadLocal与FastThreadLocal的实现机制,特别是在多线程环境下两者在性能上的差异。FastThreadLocal通过预分配固定大小的数组并为每个实例分配唯一索引,避免了hash碰撞带来的查找效率降低,从而在高并发场景下展现出更高的性能。

381

被折叠的 条评论
为什么被折叠?



