See best practices for using Java's ThreadLocal Storage including how it stores different values independently and how Java garbage collection may affect it
seen from China
seen from Dominican Republic
seen from United States

seen from United States

seen from United States
seen from United Kingdom
seen from United Kingdom

seen from Bulgaria

seen from Malaysia
seen from Malaysia

seen from United States
seen from China
seen from Philippines
seen from Thailand

seen from Malaysia
seen from Australia
seen from China

seen from Dominican Republic

seen from United States

seen from Malaysia
See best practices for using Java's ThreadLocal Storage including how it stores different values independently and how Java garbage collection may affect it

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Explaining the ThreadLocal
Introduction to ThreadLocal
Java supports multi threading and provides many high level APIs to avoid running into the issues associated with multi threading. One of the concepts we discussed previously is called synchronization. You can read about synchronization in this blog post.
Here are few scenarios I would like to draw your attention:
Thread Safety – classsic case for using ThreadLocal
Not…
View On WordPress
Storage Classes (C++)
Introduction
This blog will be covering the concept of Storage classes in the context of C++. Every variable in C/C++ has a storage class. Storage class determines the scope/lifetime, linkage and memory location of objects. A variable can have only one storage class. .Storage classes Following are the storage classes in C++.
auto
register
static
extern
mutable
thread_local
After reading this list you might have got a clear idea of what are the storage classes and what is going to be in the rest of the blog.
Auto
Auto is the default storage class of every variable. Variables defined within a block have automatic storage unless explicitly defined otherwise. Automatic objects and variables have no linkage, they are not visible to code outside the block.
{ int mount; auto int month; }
The example above defines two variables with the same storage class.
Register
In C++11, the register keyword is deprecated. It specifies that the variable is to be stored in a machine register, if possible. This means that the variable has a maximum size equal to the register size (32 or 64 bits). Like auto variables, register variables persist only until the end of the block in which they are declared.
{ register int reg_var; }
Declaring a variable as register does not mean that it will always be stored in a register. It means it MIGHT be stored in a register. If the address-of operator (&) is used on an object that is declared with register, the compiler must put the object in memory rather than a register.
Static
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.
#include <iostream> using namespace std; void showstat( int curr ) { static int nStatic; // Value of nStatic is retained // between each function call nStatic += curr; cout << "nStatic is " << nStatic << endl; } int main() { for ( int i = 0; i < 5; i++ ) showstat( i ); }
output
nStatic is 0 nStatic is 1 nStatic is 3 nStatic is 6 nStatic is 10
This example shows how a variable declared static in a function retains its state between calls to that function.
If we make a const variable static it causes that variable's scope to be restricted to the file in which it is declared.
Extern
Objects and variables declared as extern declare an object that is defined in another scope or transition unit as having external linkage. For example we declare a function header with extern keyword in one file (.cpp) and provide its implementation in another file(.cpp).
//File1.cpp
#include <iostream> int count ; extern void write_extern();
main() { count = 5; write_extern(); }
#include <iostream> extern int count; void write_extern(void) { std::cout << "Count is " << count << std::endl; }
Output
Count is 5
Mutable
Mutable storage class allows a member of an object to override constness. That is, a mutable member can be modified by a const member function.
class X { public: bool GetFlag() const { m_accessCount++; return m_flag; } private: bool m_flag; mutable int m_accessCount; };
Thread_local
This is available in C++11. A variable declared with the thread_local specifier is accessible only on the thread on which it is created. The variable is created when the thread is created, and destroyed when the thread is destroyed. Each thread has its own copy of the variable.
The thread_local specifier may be combined with static or extern. You can apply thread_local only to data declarations and definitions.
[Java] ThreadLocal을 사용할 때 주의점.
톰캣이나 제티 등의 워커쓰레드 풀을 운용하는 환경에서는, 특정 스레드에 연결된 ThreadLocal 변수들이 제대로 삭제되지 않고 남아있어 메모리 이슈를 유발한다.
때문에 이러한 관리기법 하에서는 ThreadLocal를 사용할 때 별도의 주의가 필요하다고 말하고 있다. 뭐 꼭 필요한 게 아니면 안 쓰는 편이 좋다고..
threadlocal as an alternative to syncrhonization
Use threadlocal as an alternative to syncrhonization:
An important benefit of ThreadLocal worth mentioning (from 1.4 JVMs forward), is as an alternative to synchronization, to improve scalability in transaction-intensive environments. Classes encapsulated in ThreadLocal are automatically thread-safe in a pretty simple way, since it's clear that anything stored in ThreadLocal is not shared between threads.
source: how to use threadlocal

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
ThreadLocal in Java
ThreadLocal是什么 ThreadLocal是什么呢?其实ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是thread local variable(线程局部变量)。也许把它命名为ThreadLocalVar更加合适。线程局部变量(ThreadLocal)其实的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。从线程的角度看,就好像每一个线程都完全拥有该变量。线程局部变量并不是Java的新发明,在其它的一些语言编译器实现(如IBM XL FORTRAN)中,它在语言的层次提供了直接的支持。因为Java中没有提供在语言层次的直接支持,而是提供了一个ThreadLocal的类来提供支持,所以,在Java中编写线程局部变量的代码相对比较笨拙,这也许是线程局部变量没有在Java中得到很好的普及的一个原因吧。 ThreadLocal的设计 首先看看ThreadLocal的接口: Object get() ; // 返回当前线程的线程局部变量副本 protected Object initialValue(); // 返回该线程局部变量的当前线程的初始值 void set(Object value); // 设置当前线程的线程局部变量副本的值 ThreadLocal有3个方法,其中值得注意的是initialValue(),该方法是一个protected的方法,显然是为了子类重写而特意实现的。该方法返回当前线程在该线程局部变量的初始值,这个方法是一个延迟调用方法,在一个线程第1次调用get()或者set(Object)时才执行,并且仅执行1次。ThreadLocal中的确实实现直接返回一个null: protected Object initialValue() { return null; } ThreadLocal是如何做到为每一个线程维护变量的副本的呢?其实实现的思路很简单,在ThreadLocal类中有一个Map,用于存储每一个线程的变量的副本。比如下面的示例实现: public class ThreadLocal { private Map values = Collections.synchronizedMap(new HashMap()); public Object get() { Thread curThread = Thread.currentThread(); Object o = values.get(curThread); if (o == null && !values.containsKey(curThread)) { o = initialValue(); values.put(curThread, o); } return o; } public void set(Object newValue) { values.put(Thread.currentThread(), newValue); } public Object initialValue() { return null; } } 当然,这并不是一个工业强度的实现,但JDK中的ThreadLocal的实现总体思路也类似于此。 ThreadLocal的使用 如果希望线程局部变量初始化其它值,那么需要自己实现ThreadLocal的子类并重写该方法,通常使用一个内部匿名类对ThreadLocal进行子类化,比如下面的例子,SerialNum类为每一个类分配一个序号: public class SerialNum { // The next serial number to be assigned private static int nextSerialNum = 0; private static ThreadLocal serialNum = new ThreadLocal() { protected synchronized Object initialValue() { return new Integer(nextSerialNum++); } }; public static int get() { return ((Integer) (serialNum.get())).intValue(); } } SerialNum类的使用将非常地简单,因为get()方法是static的,所以在需要获取当前线程的序号时,简单地调用: int serial = SerialNum.get(); 即可。 在线程是活动的并且ThreadLocal对象是可访问的时,该线程就持有一个到该线程局部变量副本的隐含引用,当该线程运行结束后,该线程拥有的所以线程局部变量的副本都将失效,并等待垃圾收集器收集。 ThreadLocal与其它同步机制的比较 ThreadLocal和其它同步机制相比有什么优势呢?ThreadLocal和其它所有的同步机制都是为了解决多线程中的对同一变量的访问冲突,在普通的同步机制中,是通过对象加锁来实现多个线程对同一变量的安全访问的。这时该变量是多个线程共享的,使用这种同步机制需要很细致地分析在什么时候对变量进行读写
See also: http://www.jcwcn.com/article-30276-1.html
static 변수 초기화시 throw Exception 문제...
Hibernate 레퍼런스를 보던중 예제 소스 코드를 작성하다 의문이 생겼다.
public static final SessionFactory sessionFactory; static { try { sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Exception ex) { System.err.println("initial SessionFactory"); } }
얼핏 보기에 별다른 문제가 없어 보이는 코드다 하지만 실제로 이클립스로 에서 에디팅해 보면 초기화 하지 못했다는 에러가 난다.
구글에서 검색해보니 나와 똑같은 고민을 하는 글을 발견!
http://stackoverflow.com/questions/2070293/exception-in-static-initialization-block
대충 요약을 하자면 일반적인 자바 코드 였다면 가능 했을 try{}catch{}문이 static{} 에서는 불가능하다는 것이다.
그 이유는 예외가 처리가 되어야 하는데 static{}초기화문에서는 소스코드단에서 처리가 골란하다는 것이다. 가만 생각해보니 static{}으로 초기화하게 되면 인스턴스가 생기기도 전에 초기화를 해버리니.......
그래서 Hibernate 레퍼런스 문서에서는 checked Exception을 Unchecked Exception으로 변환해서 처리 했다