这个问题让我想知道Java 和 .NET 等高级开发框架中的线程本地存储。
Java 有一个ThreadLocal<T>
类(可能还有其他结构),而 .NET 有数据槽,很快就会有ThreadLocal<T>
自己的类。(它也有ThreadStaticAttribute
,但我对成员数据的线程本地存储特别感兴趣。)大多数其他现代开发环境在语言或框架级别为它提供了一种或多种机制。
线程本地存储解决了哪些问题,或者线程本地存储相对于创建单独的对象实例以包含线程本地数据的标准面向对象惯用语提供了哪些优势?换句话说,这是怎么回事:
// Thread local storage approach - start 200 threads using the same object
// Each thread creates a copy of any thread-local data
ThreadLocalInstance instance = new ThreadLocalInstance();
for(int i=0; i < 200; i++) {
ThreadStart threadStart = new ThreadStart(instance.DoSomething);
new Thread(threadStart).Start();
}
优于这个?
// Normal oo approach, create 200 objects, start a new thread on each
for(int i=0; i < 200; i++) {
StandardInstance standardInstance = new StandardInstance();
ThreadStart threadStart = new ThreadStart(standardInstance.DoSomething);
new Thread(threadStart).Start();
}
我可以看到,使用具有线程本地存储的单个对象可能会稍微提高内存效率,并且由于分配(和构造)更少,因此需要更少的处理器资源。还有其他优点吗?