Reputation: 61
I am reading netty source code, and compare it to jdk source code. I found jdk use hash code in ThreadLocal, it is slow when there are many conflicts.
So why not use array just like FastThreadLocal in netty, no any hash conflicts, and hit directly.
Upvotes: 1
Views: 593
Reputation: 61
@Holger You are right. thank you.
After I readed JDK source code and netty source code these days, I think I got it why jdk use hash table and netty use common array。
JDK use hash table because when thread-local variables are not used anymore, the variables can be released and the hash table can be resized to avoid memory leaking. So the JDK use WeakReference as Entry to free memory automaticly and use 0x61c88647 to reduce hash conflicts.
But in netty, for search efficiency, it use common array, and not free the memory automaticly anymore. And netty can remove all thread-local variables of a thread manually, just use removeAll() method.
Upvotes: 1
Reputation: 298389
A hash based approach might be “slow when there are many conflicts”, but there is no reason to prematurely assume that there are many conflicts. Since “many hash conflicts” are a sign of a lot of elements, you’re talking about a scenario where the linear index approach has even more problems.
The FastThreadLocal
approach might be fine for applications actively using it and creating specific instances of FastThreadLocalThread
which use them.
This does not work similarly when all threads had to create an array large enough to hold a value for all ThreadLocal
instances ever created. Or, more precisely, an array usually even significantly larger, to avoid having to resize all arrays every time a ThreadLocal
is created.
You can mitigate the costs by expanding the array lazily, but that doesn’t help when setting a value for ThreadLocal
#800, when all locals with indices smaller than that have no value—or even don’t exist anymore, as this scheme has no support for automatic cleanup.
ThreadLocal
instances can get garbage collected automatically, with little impact, which is not comparable to a cleanup method that has to go through all threads, rearranging their arrays. If that ever happens. I could not find such a cleanup method in the FastThreadLocal
code. So it appears to be growing only. That’s obviously unacceptable for a standard JRE solution.
Upvotes: 4